%s and %d string formatting in Python

Want a simple way to plug values into text? Python makes that easy. In older code you might see %s and %d used for that. They are small and fast. They also show up in lots of tutorials.

What %s and %d do

%s turns almost anything into text. Use it when you want a word, name, or message printed. %d is for whole numbers. Use it when you want integers displayed. So this means you pick the one that matches the type you need.

Quick examples

Here are two short examples you can type into a file or run in the REPL.

For text:

name = "Alex"
print("Hello, %s!" % name)

For integers:

count = 5
print("You have %d new messages." % count)

Mixing values

You can put more than one in a string. Just pass a tuple of values after the % sign. The bits get filled in order.

name = "Sam"
age = 30
print("%s is %d years old." % (name, age))

It’s straightforward. If you swap the order of values, the output changes.

Formatting numbers

You can also control width and padding. Use a number between % and the letter. For example, %04d prints a number with at least four digits and left-fills with zeros.

n = 7
print("ID: %04d" % n)  # prints ID: 0007

When to use something newer

These markers still work. But newer tools exist. .format() and f-strings are easier for longer text. They read nicer and reduce mistakes. If you write new code, consider using an f-string. It keeps things clear and short.

Example with an f-string:

name = "Riley"
count = 2
print(f"{name} has {count} tasks.")

Quick tips

Keep it simple. Use %s for text and %d for integers. Match the type to avoid errors. Try f-strings for newer projects. They make the code easier to scan.

Summary

These old-school markers are handy for quick prints and small scripts. They still work fine. But for cleaner, modern code, try the newer options. You’ll save time and frustration.

Scroll to Top