Episode 7 of 29

String Formatting

Master different ways to format strings in Python — f-strings, format(), and more.

Python offers several ways to format strings with variables.

f-Strings (Recommended)

name = "Python"
version = 3
print(f"Welcome to {name} {version}!")
print(f"2 + 2 = {2 + 2}")

format() Method

print("Hello, {}!".format("World"))
print("{0} is {1}".format("Python", "awesome"))

Formatting Numbers

price = 49.99
print(f"Price: ${price:.2f}")
big = 1000000
print(f"Population: {big:,}")