SyntaxStudy
Sign Up
Python Beginner 9 min read

String Formatting

String Formatting

Python offers three main ways to format strings. f-strings (Python 3.6+) are the modern, preferred approach.

f-Strings

name = "Alice"
age = 30
pi = 3.14159
print(f"Name: {name}, Age: {age}")
print(f"Pi to 2 dp: {pi:.2f}")
print(f"Uppercase: {name.upper()}")
print(f"Calculation: {2 ** 10}")

str.format()

print("Name: {}, Age: {}".format(name, age))
print("Name: {name}, Age: {age}".format(name=name, age=age))
print("{0} is {1} and {0} likes coding".format(name, age))

%-Formatting (Legacy)

print("Name: %s, Age: %d" % (name, age))
print("Pi: %.3f" % pi)

Format Spec Mini-Language

print(f"{'left':<10}|")    # left-aligned
print(f"{'right':>10}|")   # right-aligned
print(f"{1234567:,}")       # 1,234,567
print(f"{0.1234:.1%}")      # 12.3%
Example
name = "Bob"
score = 95.678
print(f"Player: {name}")
print(f"Score: {score:.1f}")
print(f"Grade: {\"A\" if score >= 90 else \"B\"}")
print("Player: %s, Score: %.1f" % (name, score))
Pro Tip

f-strings are evaluated at runtime, so you can embed any valid Python expression inside the curly braces.