What's the difference between %s and %d in Python string formatting?


Question

I don't understand what %s and %d do and how they work.

1
111
9/22/2016 5:07:10 PM

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

name = 'marcog'
number = 42
print '%s %d' % (name, number)

will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).

See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting for details.

In Python 3 the example would be:

print('%s %d' % (name, number))
162
6/12/2018 8:45:15 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon