Tip: 2 ways to format a string in Python
Isabelle M.
Posted on July 28, 2022
f-string
Formatted string literals, commonly known as f-strings, are strings prefixed with 'f
' or 'F'
. These strings can contain replacement fields, enclosed in curly braces ({}
).
name = 'John'
age = 32
print(f'{name} is {age} years old') # 'John is 32 years old'
str.format()
The str.format()
method works very much alike f-strings, the main difference being that replacement fields are supplied as arguments instead of as part of the string.
name = 'John'
age = 32
print('{0} is {1} years old'.format(name, age)) # 'John is 32 years old'
Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨💻
💖 💪 🙅 🚩
Isabelle M.
Posted on July 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev 🎉 Dive into Python 3.13: New Features, JIT Compiler, Free threading & Installation Guide! 🎉
November 12, 2024