
f-strings (Python 3.6+) — USE THESE:
name = "Alice"
pi = 3.14159
print(f"Hello {name}")
print(f"Pi is {pi:.2f}") # 2 decimal places
print(f"{1000000:,}") # 1,000,000
print(f"{0.856:.1%}") # 85.6%
print(f"{name!r}") # repr: 'Alice'
print(f"{name:>20}") # right-align in 20 chars.format() method:
"{} is {}".format("Alice", 30)
"{name} is {age}".format(name="Alice", age=30)
"{0:.2f}".format(3.14159) # 3.14% formatting (old style, avoid):
"Hello %s, you are %d" % ("Alice", 30)Format spec cheat sheet:
:.2f — 2 decimal places
:, — thousands separator
:>10 — right align width 10
:<10 — left align width 10
:^10 — center width 10
:05d — zero-padded integer
Reference:
TaskLoco™ — The Sticky Note GOAT