183

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

13 Answers 13

236

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))
3
  • 2
    In Google Chrome: Settings >> Search >> Manage search engines... notice how %s is used with search engine configurations. Chrome uses %s to replace keywords entered in the address bar. Python uses %s in a similar way. In print('description: %s' % descrip) the %s operator will be replaced by the text string stored in the descrip variable. The round braces prevent an error message in Python 3.
    – noobninja
    Aug 27, 2016 at 20:51
  • what do you call these %s, %d, etc?
    – Chaine
    May 19, 2017 at 18:21
  • 1
    @Chaine they are called Placeholders, they are replaceable variables
    – Leo
    Jun 9, 2017 at 19:44
76

from python 3 doc

%d is for decimal integer

%s is for generic string or object and in case of object, it will be converted to string

Consider the following code

name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))

the out put will be

giacomo 4.3 4 4.300000 4.3

as you can see %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number

obviously

print('%d' % (name))

will generate an exception; you cannot convert string to number

2
  • 8
    This deseeves more upvote. It explains what would happen if %s is used for a number instead. Sep 1, 2018 at 13:41
  • 2
    What is the difference between %d and %i, if both will convert to integer? How does %d compare to %i and %f ?
    – srini
    Jul 22, 2019 at 12:05
40

%s is used as a placeholder for string values you want to inject into a formatted string.

%d is used as a placeholder for numeric or decimal values.

For example (for python 3)

print ('%s is %d years old' % ('Joe', 42))

Would output

Joe is 42 years old
2
  • 7
    Doesn't really explain the problem? I'm not explaining the problem, I'm providing a concise answer to the question. The question specifically asked what %s and %d were for.
    – Soviut
    Feb 16, 2012 at 2:37
  • 3
    do you know the difference between %i and %d? does python support %i?
    – cryanbhu
    Oct 31, 2018 at 1:43
39

These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

>>> '%d' % 0x15
'21'

or truncate a float.

>>> '%d' % 34.5
'34'

But the operation will raise an exception if the argument isn't a number.

>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is str.

>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

The same is true with string.format; the default is str.

>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'
2
  • 4
    This should be the accepted answer. It's the only one that actually explains the difference.
    – Antimony
    Sep 23, 2020 at 19:09
  • 2
    Given that I answered 9 years late, it's understandable. But, I was not satisfied with the answers so I added one.
    – Wyrmwood
    Sep 29, 2020 at 20:51
11

These are placeholders:

For example: 'Hi %s I have %d donuts' %('Alice', 42)

This line of code will substitute %s with Alice (str) and %d with 42.

Output: 'Hi Alice I have 42 donuts'

This could be achieved with a "+" most of the time. To gain a deeper understanding to your question, you may want to check {} / .format() as well. Here is one example: Python string formatting: % vs. .format

also see here a google python tutorial video @ 40', it has some explanations https://www.youtube.com/watch?v=tKTZoB2Vjuk

10

The %d and %s string formatting "commands" are used to format strings. The %d is for numbers, and %s is for strings.

For an example:

print("%s" % "hi")

and

print("%d" % 34.6)

To pass multiple arguments:

print("%s %s %s%d" % ("hi", "there", "user", 123456)) will return hi there user123456

1
  • 1
    Note that %d is not any number. it's a decimal number (aka, integers). In the example above, %d' %34.6 will output simply 34. Same applies to logger.info("value %d", 34.6) Feb 1, 2022 at 0:21
9

%d and %s are placeholders, they work as a replaceable variable. For example, if you create 2 variables

variable_one = "Stackoverflow"
variable_two = 45

you can assign those variables to a sentence in a string using a tuple of the variables.

variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"

Note that %s works for String and %d work for numerical or decimal variables.

if you print variable_3 it would look like this

print(variable_3 % (variable_one, variable_two))

I was searching for an answer in StackOverflow and found more than 45 answers to my question.

4

As per latest standards, this is how it should be done.

print("My name is {!s} and my number is{:d}".format("Agnel Vishal",100))

Do check python3.6 docs and sample program

4

Here is the basic example to demonstrate the Python string formatting and a new way to do it.

my_word = 'epic'
my_number = 1

print('The %s number is %d.' % (my_word, my_number))  # traditional substitution with % operator

//The epic number is 1.

print(f'The {my_word} number is {my_number}.')  # newer format string style

//The epic number is 1.

Both prints the same.

3

speaking of which ...
python3.6 comes with f-strings which makes things much easier in formatting!
now if your python version is greater than 3.6 you can format your strings with these available methods:

name = "python"

print ("i code with %s" %name)          # with help of older method
print ("i code with {0}".format(name))  # with help of format
print (f"i code with {name}")           # with help of f-strings
3

%s is used to hold space for string %d is used to hold space for number

name = "Moses";
age = 23
print("My name is %s am CEO at MoTech Computers " %name)
print("Current am %d years old" %age)
print("So Am %s and am %d years old" %(name,age))

Program output

this video goes deep about that tip https://www.youtube.com/watch?v=4zN5YsuiqMA

4
  • Welcome to Stack Overflow! How is your answer different the other 12? Feb 17, 2020 at 23:13
  • almost those format works the same but all i wanted is to give more examples so as to increase an understanding Feb 20, 2020 at 17:25
  • That's great! You can improve your answer by adding the program output as a text and not as an image. Feb 20, 2020 at 19:13
  • thanks for your concern, i'll make some changes, you're welcome Feb 25, 2020 at 19:40
2

In case you would like to avoid %s or %d then..

name = 'marcog'
number = 42
print ('my name is',name,'and my age is:', number)

Output:

my name is marcog and my name is 42
4
  • 2
    What does this answer have to do with the question? The questioner was asking about use of %s and %d. Feb 3, 2016 at 15:09
  • BTW, the code you show is invalid in Python 3.5.1: print is a function in Python 3, not a statement. Feb 3, 2016 at 15:10
  • I have edited the post ...please see it. Actually, I posted it as an alternative..if some one might avoid using %d or %s. And thanks for the error detection, ..I have edited the code.
    – Sujatha
    Feb 3, 2016 at 17:37
  • 4
    Thanks for the edits. Unfortunately, this still isn't an answer to the question. Feb 3, 2016 at 18:03
0

for example you can use %s and %d and %f like as below:

name = 'Ali' ;age = 25  ; live = 'Tehran' ; salary = 1526.73

print('%s is %d years old. he is living in %s and earn %f per month.' % (name, age, live, salary))
New contributor
Mohammad Mahdi Bazrafshan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2
  • 1
    How is this answer different than the ones posted before? For example this one, this one, and this one? yesterday
  • It is especially important to check existing answers on old questions like this one (it was asked 13 years ago).
    – Chris
    11 hours ago

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.