📝

How to Format Strings in Python

PythonBeginner

Format strings with f-strings, format(), and %.

Code Example

Python
name = "Alice"
age = 30
height = 5.6

# F-strings (Python 3.6+)
print(f"Name: {name}")
print(f"Age: {age}, Height: {height}")

# Format numbers
pi = 3.14159265359
print(f"\nPi: {pi:.2f}")  # 2 decimal places
print(f"Pi: {pi:.4f}")  # 4 decimal places
print(f"Large: {1000000:,}")  # With commas

# Padding and alignment
print(f"\n'{name:<10}' (left)")
print(f"'{name:>10}' (right)")
print(f"'{name:^10}' (center)")

# Format method
print("\nFormat method:")
print("Name: {}, Age: {}".format(name, age))
print("Name: {0}, Age: {0}".format(name))  # Reuse
print("{:>10} {:>10}".format("Item", "Price"))

# Old style % formatting
print("\nOld style:")
print("Name: %s, Age: %d" % (name, age))
print("Pi: %.2f" % pi)

# Expressions in f-strings
print(f"\n2 + 2 = {2 + 2}")
print(f"Uppercase: {name.upper()}")

Explanation

F-strings (f"...") are modern and readable. Use .format() for older code. % formatting is legacy. F-strings support expressions.

Related Tutorials