✨
String Formatting
Format text with f-strings and .format()
Reward
+40 XP
f-strings (recommended)
Prefix a string with f and put expressions in curly braces.
name = "Alice"
age = 30
print(f"{name} is {age} years old").format() method
An older style using placeholders {}.
print("Hello, {}! You are {}.".format("Bob", 25))Number formatting
Control decimal places, padding, and alignment.
pi = 3.14159
print(f"Pi is {pi:.2f}")
print(f"{'hello':>20}")
print(f"{42:05d}")Try it yourself
Run the example below. Edit it and see what changes.
main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)
Common mistakes
- ⚠Forgetting the f prefix in f-strings.
- ⚠Mixing f-string and .format() in the same string.
