String formatting lets you insert variables and expressions into a string in a clean, readable way. Python supports several approaches, including modern f-strings and the older str.format() method, which help you control text, numbers, alignment and overall layout.
f"...{expression}...") in Python 3.6+ for concise formatting.format() method for older Python versions or when f-strings are not available.{pi:.2f}).An f-string is written by prefixing a string with f, for example: f"My name is {name}". Any valid Python expression inside {...} will be evaluated and converted to a string.
The format() method works by using placeholders inside a string: "My name is {}".format(name). You can also use numbered placeholders ({0}, {1}) or named placeholders ({n}, {a}).
For numbers, you can add a format specifier after a colon, such as {pi:.2f} (2 decimal places) or {pi:10.3f} (width 10, 3 decimal places). Alignment uses < (left), > (right) and ^ (center) along with a width, for example {text:<10}.
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
name = "Alice"
age = 25
message1 = "Name: {0}, Age: {1}".format(name, age)
message2 = "Name: {n}, Age: {a}".format(n=name, a=age)
print(message1)
print(message2)
pi = 3.14159
print(f"Pi rounded: {pi:.2f}") # 3.14
print("Pi rounded: {:.3f}".format(pi)) # 3.142
text = "Python"
print(f"{text:<10}X") # Left align
print(f"{text:>10}X") # Right align
print(f"{text:^10}X") # Center align
format() examples both print: My name is Alice and I am 25 years old.Name: Alice, Age: 25 twice, once using positions and once using named placeholders.3.14159 to: 3.14 (2 decimal places) and 3.142 (3 decimal places).Python inside a field of width 10, with an extra X character showing where the padding ends: left-aligned, right-aligned, and centered.Together, these examples show how formatting helps you build clean, readable console output and properly aligned text for tables, logs, and reports.
.format() when you must support Python versions earlier than 3.6.f prefix when using f-strings, otherwise {...} will not be evaluated.format(), make sure placeholders and arguments match to avoid IndexError or KeyError.format() method.<, >, ^).format() to neatly display your name, age, and city.