An f-string lets you build readable text from words, variables, and expressions. It is useful for greetings, game results, program messages, and colored terminal text.
Your First f-String
Place the letter f before the opening quote and put the variable name inside curly braces {}:
name = 'Alex'
level = 5
message = f'Player: {name}. Level: {level}.'
print(message)
Python replaces {name} and {level} with their values:
Player: Alex. Level: 5.
Variables must be created before the f-string. Without the letter f, the braces remain ordinary text.
Expressions Inside Braces
You can put a simple expression inside the braces:
score = 40
bonus = 10
print(f'Total score: {score + bonus}')
Calculate complex values beforehand and store them in a variable so the code remains easy to read.
Why + Does Not Always Work
Adding a string and a number raises TypeError:
age = 16
# print('Age: ' + age) # TypeError
You could convert the number with str(age), but an f-string is usually clearer:
print(f'Age: {age}')
Another valid option is to pass separate values to print() with a comma:
print('Age:', age)
Multiline f-Strings
The f prefix also works with triple quotes:
name = 'Alex'
status = f"""Pilot: {name}
Status: ready to launch"""
print(status)
If a multiline drawing contains backslashes, you can combine the f and r prefixes:
color = '\033[91m'
reset = '\033[0m'
rocket = fr"""{color}
/\
/__\
{reset}"""
print(rocket)
In an fr string, f inserts values while r preserves backslashes written in the string itself.
Common Mistakes
- The output contains
{name}โ addfbefore the opening quote. NameErrorโ create the variable first and check its spelling.SyntaxErrorโ check matching quotes, parentheses, and braces.- You need braces as text โ double them:
f'{{name}}'prints{name}.
Key Points
- place
fimmediately before the opening quote; - write values and expressions inside
{}; - create variables before using them;
- use
frwhen you need both substitutions and literal backslashes.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!