capypad
0 day streak
python / beginner
Snippet

Modern String Formatting with f-strings

f-strings (formatted string literals) allow you to embed Python expressions inside string literals using curly braces. They are more readable and faster than older formatting methods like % or .format().

snippet.py
python
1
2
3
4
5
6
7
name = "Python"
version = 3.12
 
# Combine variables and expressions inside a string
message = f"Welcome to {name} version {version}!"
 
print(message)
Breakdown
1
f"Welcome to..."
The 'f' prefix tells Python to evaluate the expressions inside the curly braces.
2
{name}
The value of the variable 'name' is converted to a string and inserted here.