Using the percent (%) symbol in Python string formatting
Contents
Old-style string formatting in Python uses the percent sign. It looks different than f-strings or .format, but it still works and can be handy. This guide keeps things simple. Short examples. Easy explanations.
What is it and why use it?
The percent symbol lets you inject values into strings. You write a template with placeholders, then give the values. It’s fast to type. It’s also familiar if you know C-style formatting.
Basic example
Use %s for text and %d for whole numbers.
name = "Alex"
age = 30
print("My name is %s and I am %d years old." % (name, age))
That prints: My name is Alex and I am 30 years old.
Floating numbers
Use %f for floats. Add precision like .2 to round.
pi = 3.14159
print("Pi rounded: %.2f" % pi) # Pi rounded: 3.14
Escaping the percent sign
If you want a real percent sign in the output, use %%. The first percent is the escape. The second is the output.
score = 95
print("You scored %d%% on the test." % score) # You scored 95% on the test.
Multiple values and tuples
When you insert more than one value, pass a tuple.
item = "apples"
count = 5
print("I bought %d %s today." % (count, item)) # I bought 5 apples today.
Named placeholders with dictionaries
You can name placeholders and pass a dict. This helps when order matters or when the same value appears more than once.
data = {"name": "Sam", "score": 88}
print("Player: %(name)s, Score: %(score)d" % data)
Width, alignment, and padding
You can set field width and alignment. Use a number between % and the type letter.
print("%10s" % "hello") # right-align in 10 spaces
print("%-10s" % "hello") # left-align in 10 spaces
print("%8.2f" % 3.14159) # width 8, 2 decimals
Common mistakes
Forgot to use a tuple for multiple values? That breaks the code. Mix up %s and %d and you’ll see errors. And don’t forget to escape a real percent sign with %%. These are the usual traps.
So how does this effect you?
If you maintain older code, you’ll see this pattern a lot. It’s fine to keep using it, but newer projects often prefer .format or f-strings. Still, knowing it helps when you read other people’s code or quick scripts.
Quick cheat sheet
– %s : string
– %d : integer
– %f : float (use .2 for two decimals)
– %% : literal percent sign
– %(name)s : named placeholder from a dict
Short and sweet. Try a few examples. You’ll get the hang of it fast.


