Python f-strings Formatted String Literals Syntax and Examples

In PEP 498 a new string formatting mechanism was introduced called as "Literal String Interpolation" or more famously called as f-strings.

The Python f-strings are a way by which you can embed expressions inside string literals. It makes use of a very minimal syntax (prefixed with the word 'f').

Let us take a look at the Syntax:

f"Some String Literal {expression-1} more text {expression-2}"

Note: The f-string literal string expressions are evaluated at run-time, and they are expressed with curly braces as shown above.


Example 1:
user = 'Mike'
f'The user name is {user}'

'The user name is Mike'


Example 2: f-strings with print function
name = 'Alex'
age = 22
city = 'New York'

print(f"The name is {user}, age is {age}, city {city}")

The name is Mike, age is 22, city New York


The f-string was designed with the intention to have a simpler way to format strings in Python as the existing ways of formatting are either error-prone, inflexible, or cumbersome.

Further readings:

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap