How to print formatted string in Python3?
How can you print a formatted string in Python 3?
This question explores the different ways to format and print strings in Python 3 using techniques like f-strings, format(), and the % operator for clean and readable output.
In Python 3, printing a formatted string is super easy and flexible thanks to multiple formatting methods. Whether you're displaying variables, numbers, or text with specific alignment or precision, Python gives you several options.
1. Using f-strings (Recommended – Python 3.6+)
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Clean and readable
Allows inline expressions and even formatting like:
price = 12.3456
print(f"Price: {price:.2f}") # Output: Price: 12.35
2. Using .format() method
print("My name is {} and I am {} years old.".format(name, age))
- Works in all Python 3 versions
- Can be used with named or positional placeholders:
print("Name: {n}, Age: {a}".format(n="Bob", a=25))
3. Using % operator (Old-school)
print("Name: %s, Age: %d" % (name, age))
- Still works, but less preferred in modern Python code
- Good for those coming from C-style languages
So, the best way to print formatted strings in Python 3 is by using f-strings—they're concise, readable, and super powerful. But it's good to know .format() and % exist, especially when working with legacy code.