f-string (f-String Literals)
A syntax for embedding variables and expressions directly inside strings. The f-string (f-string), introduced in Python 3.6, is a widely used method of string interpolation in Python.
Syntax
# Prefix the string literal with f or F.
f"text {variable} text"
f'text {variable} text'
# Expressions can be written inside {}.
f"{expression}"
f"{object.method()}"
# Format specifiers control how numbers are displayed.
f"{number:.2f}" # 2 decimal places
f"{number:,}" # comma separator
f"{number:,.2f}" # comma + 2 decimal places
f"{number:.1%}" # percentage notation
# Debug = notation (Python 3.8+).
f"{variable=}" # outputs in the form variable=value
Format Specifier Reference
| Format Specifier | Notes |
|---|---|
| :.2f | Displays a floating-point number with 2 decimal places. The digit count can be changed freely. |
| :, | Displays integers and floats with comma separators every 3 digits. |
| :,.2f | Combines comma separator with a specified number of decimal places. |
| :.1% | Converts a float to percentage notation (0.856 → 85.6%). |
| :0Nd | Zero-pads an integer to N digits (e.g. :03d → 007). |
| :>N / :<N / :^N | Right-aligns / left-aligns / centers a string within width N. |
| :x / :X | Displays an integer in hexadecimal (lowercase / uppercase). |
| :b | Displays an integer in binary. |
| = (debug notation) | Writing f"{variable=}" outputs in the form "variable=value" (Python 3.8+). |
Sample Code
f_string_basic.py
# Using KOF (The King of Fighters) character data
# to check the basic usage of f-strings.
# --- f-string basics ---
name = "Kusanagi Kyo"
team = "Japan Team"
wins = 42
# Embed variables directly.
print(f"Fighter: {name}") # Fighter: Kusanagi Kyo
print(f"Team: {team}, Wins: {wins}") # Team: Japan Team, Wins: 42
# Single-quote f-strings work the same way.
print(f'Name: {name}') # Name: Kusanagi Kyo
# --- Calculations inside {} ---
damage = 350
combo_multiplier = 1.25
# Expressions can be written directly inside {}.
print(f"Combo damage: {damage * combo_multiplier}") # Combo damage: 437.5
print(f"Combo damage: {damage * combo_multiplier:.0f}") # Combo damage: 438 (integer display)
# --- Method calls ---
move = "orochi nagi"
# Methods can be called inside {}.
print(f"Special move: {move.upper()}") # Special move: OROCHI NAGI
print(f"Character count: {len(move)}") # Character count: 10
print(f"Title case: {move.title()}") # Title case: Orochi Nagi
f_string_format.py
# Use format specifiers to control how numbers are displayed.
# --- Decimal places ---
power_level = 9847.3621
print(f"Power: {power_level:.2f}") # Power: 9847.36 (2 decimal places)
print(f"Power: {power_level:.0f}") # Power: 9847 (rounded to integer)
# --- Comma separator ---
prize_money = 5000000
print(f"Prize: {prize_money:,}") # Prize: 5,000,000
# --- Comma separator + decimal places ---
score = 1234567.89
print(f"Score: {score:,.1f}") # Score: 1,234,567.9
# --- Percentage notation ---
win_rate = 0.7843
print(f"Win rate: {win_rate:.1%}") # Win rate: 78.4%
# --- Zero padding ---
player_id = 7
print(f"Player ID: {player_id:03d}") # Player ID: 007 (3 digits, zero-padded)
# --- String alignment ---
fighters = ["Kusanagi Kyo", "Yagami Iori", "Terry Bogard"]
print("-" * 30)
for fighter in fighters:
# Left-aligned with width 20 (:<20 means left-aligned).
print(f"{fighter:<20} *")
# Kusanagi Kyo *
# Yagami Iori *
# Terry Bogard *
# --- Base conversion ---
fighter_code = 255
print(f"Decimal: {fighter_code:d}") # Decimal: 255
print(f"Hex: {fighter_code:x}") # Hex: ff
print(f"Hex: {fighter_code:X}") # Hex: FF (uppercase)
print(f"Binary: {fighter_code:b}") # Binary: 11111111
f_string_quote_debug.py
# Handling nested quotes and the debug notation.
# --- Nested quotes ---
# Single quotes can be used inside f"...".
team_dict = {"leader": "Kusanagi Kyo", "rival": "Yagami Iori"}
print(f"Leader: {team_dict['leader']}") # Leader: Kusanagi Kyo
# Double quotes can be used inside f'...'.
print(f'Rival: {team_dict["rival"]}') # Rival: Yagami Iori
# Python 3.12+ allows nested same-type quotes.
# (In earlier versions this causes SyntaxError, so the above approach is safer)
# --- Debug = notation (Python 3.8+) ---
damage = 350
combo = 3
win_rate = 0.784
# Displays both the variable name and its value. Very useful for print debugging.
print(f"{damage=}") # damage=350
print(f"{combo=}") # combo=3
print(f"{win_rate=}") # win_rate=0.784
# Format specifiers can be combined with =.
print(f"{win_rate=:.1%}") # win_rate=78.4%
print(f"{damage * combo=}") # damage * combo=1050 (expressions are shown as-is)
# --- Multi-line f-strings ---
name = "Kusanagi Kyo"
team = "Japan Team"
wins = 42
# Long f-strings can be written across lines using parentheses.
profile = (
f"Name: {name}\n"
f"Team: {team}\n"
f"Wins: {wins}"
)
print(profile)
# Name: Kusanagi Kyo
# Team: Japan Team
# Wins: 42
python3 f_string_basic.py Fighter: Kusanagi Kyo Team: Japan Team, Wins: 42 Name: Kusanagi Kyo Combo damage: 437.5 Combo damage: 438 Special move: OROCHI NAGI Character count: 10 Title case: Orochi Nagi
python3 f_string_format.py Power: 9847.36 Power: 9847 Prize: 5,000,000 Score: 1,234,567.9 Win rate: 78.4% Player ID: 007 ------------------------------ Kusanagi Kyo * Yagami Iori * Terry Bogard * Decimal: 255 Hex: ff Hex: FF Binary: 11111111
python3 f_string_quote_debug.py Leader: Kusanagi Kyo Rival: Yagami Iori damage=350 combo=3 win_rate=0.784 win_rate=78.4% damage * combo=1050 Name: Kusanagi Kyo Team: Japan Team Wins: 42
Common Mistakes
Common Mistake 1: Backslash cannot be written directly inside {} of an f-string
Writing a backslash directly inside {} of an f-string causes a SyntaxError. Values containing backslashes should be stored in a variable first and then used.
ng_backslash.py
# NG: a backslash cannot be written directly inside {}.
fighters = ["Kusanagi Kyo", "Yagami Iori", "Terry Bogard"]
print(f"Fighters: {'\n'.join(fighters)}")
python3 ng_backslash.py
File "ng_backslash.py", line 3
print(f"Fighters: {'\n'.join(fighters)}")
^
SyntaxError: f-string expression part cannot include a backslash
ok_backslash.py
# OK: store values containing backslashes in a variable first.
fighters = ["Kusanagi Kyo", "Yagami Iori", "Terry Bogard"]
separator = "\n"
print(f"Fighters:\n{separator.join(fighters)}")
python3 ok_backslash.py Fighters: Kusanagi Kyo Yagami Iori Terry Bogard
Common Mistake 2: Using :d on a float causes ValueError
:d is a format specifier for integers only. Using it on a float variable causes a ValueError. To display a float without decimal places, use :.0f.
ng_float_d.py
# NG: :d cannot be used with float.
win_rate = 78.4
print(f"Win rate: {win_rate:d}%")
python3 ng_float_d.py
Traceback (most recent call last):
File "ng_float_d.py", line 3, in <module>
print(f"Win rate: {win_rate:d}%")
ValueError: Unknown format code 'd' for object of type 'float'
ok_float_d.py
# OK: use :.0f to display a float as an integer.
win_rate = 78.4
print(f"Win rate: {win_rate:.0f}%")
# Converting to int first and then using :d is also possible.
print(f"Win rate: {int(win_rate):d}%")
python3 ok_float_d.py Win rate: 78% Win rate: 78%
Common Mistake 3: Quote conflict when accessing a dict inside an f-string
Using the same type of quote inside and outside an f-string causes a SyntaxError. If the outer quotes are double, use single quotes inside; if the outer quotes are single, use double quotes inside.
ng_quote_conflict.py
# NG: same type of quotes used inside and outside (Python 3.11 and earlier).
team = {"leader": "Kusanagi Kyo", "rival": "Yagami Iori"}
print(f"Leader: {team["leader"]}")
python3 ng_quote_conflict.py
File "ng_quote_conflict.py", line 3
print(f"Leader: {team["leader"]}")
^^^^^^
SyntaxError: f-string: unmatched '['
ok_quote_conflict.py
# OK: use different quote types inside and outside.
team = {"leader": "Kusanagi Kyo", "rival": "Yagami Iori"}
# Outer double quotes -> inner single quotes.
print(f"Leader: {team['leader']}")
# Outer single quotes -> inner double quotes.
print(f'Rival: {team["rival"]}')
python3 ok_quote_conflict.py Leader: Kusanagi Kyo Rival: Yagami Iori
Notes
An f-string is activated by prefixing a string literal with 'f' or 'F'. Inside '{}', not just variables but any expression — calculations, method calls, function calls — can be written. However, statements and assignments (except the := walrus operator) cannot be used, so complex processing should be stored in a variable first and then embedded.
Format specifiers are specified in the form '{value:format}'. The most commonly used patterns are ':.2f' (2 decimal places), ':,' (comma separator), and ':.1%' (percentage). To display a float as an integer, use '{:.0f}'. Using '{:d}' (the integer format specifier) on a float causes a ValueError.
The 'f"{variable=}"' debug notation is available from Python 3.8. It displays both the variable name and its value, making it useful for print debugging. For nested quotes, using single quotes inside f"..." and double quotes inside f'...' is the safe approach. For other string formatting methods, see 'str.format() / f-strings'.
If you find any errors or copyright issues, please contact us.