3

Before you get mad at me for asking this question, I have looked for the answer but still can't seem to get what exactly they do. I saw this one answer by a user named "marcog" on SOF. For example :

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

What I did then was deleting this part and the code still outputs the exact same thing.

name = "marcog"
number = 42
print(name, number)

Could you please briefly explain the reason we use them ? By the way, I'm using 3.3.1.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
kiasy
  • 304
  • 3
  • 6
  • 17
  • 2
    possible duplicate of [%s and %d python](http://stackoverflow.com/questions/4288973/s-and-d-python) – Ashwini Chaudhary Jun 12 '13 at 19:28
  • 2
    Not really a duplicate. – dansalmo Jun 12 '13 at 19:32
  • As Steve's answer shows, the difference is not very meaningful when literally all you are doing is print out the two variables with a space between them, but when you use format specifiers like %d and %s in the middle of a larger string, then the difference becomes much more obvious. The format specifiers also, in some cases, enable you to specify more formatting information, such as the width of the field, the number of decimal places, and so on. – Crowman Jun 12 '13 at 20:18

3 Answers3

12

It tells print to output a string (%s) and a signed integer (%d). This is more useful if you want to have a more complicated output. For example:

print("Hello %s your number is %d" % (name, number))

With the sample values you've given, this will output:

Hello marcog your number is 42

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Steve
  • 7,171
  • 2
  • 30
  • 52
6

They are used for string formatting (mainly inclusion of variables) with the % (modulo) operator. It is heavily based on C's standard lib printf call - the complete docs are here:

http://docs.python.org/2/library/stdtypes.html#string-formatting

jsbueno
  • 99,910
  • 10
  • 151
  • 209
2

String formatting is a string operation, so it doesn't necessarily need to be used with a print statement.

my_string = "%s %d"%("foo bar", 5)
foo, bar, five = my_string.split()
print("%s %d %s"%(bar, five, foo))
chepner
  • 497,756
  • 71
  • 530
  • 681