In programming, we often need to display text alongside numbers or variables. Imagine you’re building a game and need to show the player’s level and score.
💔 Why the Old Way Is Awkward
Traditionally you had to “glue” text and numbers together like building blocks, using commas or plus signs:
name = "Wanderer"
level = 5
gold = 150
print("Hello, " + name + "! Your level: " + str(level) + ", gold: " + str(gold) + " coins.")
Look at all those quotes and plus signs! On top of that, numbers (like level) have to be explicitly converted to strings with str(), otherwise Python raises an error (you can’t just add text and a number). It’s tedious, easy to get confused, and prone to typos.
💖 The Beautiful Way: f-strings!
Starting with Python 3.6, a real piece of magic arrived — f-strings. The f stands for format.
To use them, simply put the letter f (lowercase) before the opening quote. Then write variables directly inside the string, wrapped in curly braces { }.
Look how simple it is:
name = "Wanderer"
level = 5
gold = 150
# The f before the quote makes this string magical!
print(f"Hello, {name}! Your level: {level}, gold: {gold} coins.")
How does it work?
The curly braces {} act like little portals. Python sees them, knows there’s a variable (or even a math expression!) inside, evaluates it, and substitutes the result right into the string. The text reads naturally in one go!
🧮 What Else Can f-strings Do?
You can run math expressions directly inside the braces!
# For example, let's calculate spell damage:
base_damage = 20
bonus_fire = 15
print(f"The magic ball deals {base_damage + bonus_fire} points of damage!")
# Output: The magic ball deals 35 points of damage!
The key rules to remember:
- Put f at the very start (no space before the quote): f"My text"
- Variables go inside {} (curly braces)
- Reads like natural language and looks like plain text — ideal for a beginning engineer!
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!