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.



Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more