DEV Community

Cover image for Learn Python: Formatting strings
Rishi
Rishi

Posted on • Edited on

2 1

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.



Please leave your appreciation by commenting on this post!

It takes one minute and is worth it for your career.

Get started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay