简体   繁体   中英

What's the purpose of %d and %s

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.

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

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM