String Formatting (% Operator)#
Note
Prefer f-strings
The % formatting operator is a legacy approach. In modern Python (3.6+), f-strings are the preferred method for string formatting. See Strings for details on f-strings.
The % operator allows you to embed values inside a string using conversion specifications.
Syntax#
"format string" % (values)
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))
# Name: Alice, Age: 30
Conversion Specification Pattern#
%[flags][width][.precision]code
Each % placeholder in the string follows this pattern.
Conversion Codes#
Code |
Description |
Example |
|---|---|---|
|
String (or any object via |
|
|
Integer (decimal) |
|
|
Floating-point (default 6 decimals) |
|
|
Floating-point in scientific notation |
|
|
Single character (int or str) |
|
Flags#
Flag |
Description |
Example |
|---|---|---|
|
Left-align within the field width |
|
|
Show sign for positive numbers |
|
|
Insert space before positive numbers |
|
|
Alternate form ( |
|
|
Zero-pad numbers |
|
Width#
Minimum number of characters in the output. Pads with spaces (or zeros if 0 flag is used).
print("%10s" % "hi") # hi (right-aligned, 10 chars wide)
print("%-10s!" % "hi") # hi ! (left-aligned)
print("%10d" % 42) # 42
Precision#
For floats, specifies the number of decimal places. For strings, specifies the maximum length.
print("%.2f" % 3.14159) # 3.14
print("%.4f" % 3.14159) # 3.1416
print("%.3s" % "hello") # hel
Combined Examples#
# Right-aligned float with 2 decimal places, 8 chars wide
print("%8.2f" % 3.14159) # 3.14
# Zero-padded integer, 5 chars wide
print("%05d" % 42) # 00042
# Multiple values
x, y = 10.5, 20.3
print("Point: (%.1f, %.1f)" % (x, y)) # Point: (10.5, 20.3)
# Dictionary-based formatting
data = {"name": "Alice", "score": 95.5}
print("%(name)s scored %(score).1f%%" % data) # Alice scored 95.5%