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%