๐Ÿ“ Python

Python f-Strings: Insert Values into Text ๐Ÿช„

P
Author
PyLand Team
๐Ÿ“…
Published
30.03.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
437
๐ŸŒฑ
Level
Beginner

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} โ€” add f before 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 f immediately before the opening quote;
  • write values and expressions inside {};
  • create variables before using them;
  • use fr when you need both substitutions and literal backslashes.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

if __name__ == "__main__": the Python entry point

The if name == "main" guard defines a Python program's entry point: it distinguishes direct...

๐Ÿ“… 14.08.2026 ๐Ÿ‘๏ธ 44
๐Ÿ“

strip() and lower(): Preparing User Text ๐Ÿงน

A user may enter the correct word with extra spaces or different letter case. Python...

๐Ÿ“… 11.08.2026 ๐Ÿ‘๏ธ 50
๐Ÿ“

ord(), chr(), and Cyclic Letter Shifts in Python ๐Ÿ”

A string contains characters, but a computer stores every character as a numeric code. Python...

๐Ÿ“… 09.08.2026 ๐Ÿ‘๏ธ 89