DEV Community

Cover image for Learn Python: Formatting strings
Rishi
Rishi

Posted on • Updated on

Learn Python: Formatting strings

f-strings

Available in Python version 3.6 and above.
To avoid string concatenations, we can use f-string to 'inject' values within a string via variables.

Pre-pending an f before a string will cause the variable between {} to be evaluated.

# f-strings
year = 2020
print(f"The year is {year}")
print(f'The year is {year}')

question = f"Which year comes after {year}?"
print(question)
Enter fullscreen mode Exit fullscreen mode

Updating the variable after 'f-string' has been evaluated.

Since the f-string has been evaluated with the variable year set to 2020. Re-assigning it to a new value 9999 afterwards will not update the f-string automatically.

# f-strings
# Updating variable value after assignment.
year = 2020
message = f"The year is {year}."
print(message)

year = 9999
print(message)
Enter fullscreen mode Exit fullscreen mode

Using string.format()

Another way of formatting a string is by using string.format().
Passing the variable name to format(name), will inject its value into the {} of the variable template.

name = 'Rishi'
template = 'How are you {}?'
fomatted_greeting = template.format(name)
print(fomatted_greeting)

name = 'Abee'
fomatted_greeting = template.format(name)
print(fomatted_greeting)
Enter fullscreen mode Exit fullscreen mode

Using named variables

Using named variables makes the template more readable.

name1 = 'Rishi'
name2 = 'Abee'
template = 'How are you {x} {y}?'
fomatted_greeting = template.format(x=name1, y=name2)
print(fomatted_greeting)
Enter fullscreen mode Exit fullscreen mode

f-strings v/s string.format()

f-strings is very common in Python.
But if you have a template and you want to re-use it, string.format() comes in very handy.



Top comments (0)