Shameer
Shameer

Reputation: 189

What does the `s` in `%s` mean in string formatting?

I have just started reading learn python the hard way and I have a question.

for example the code will be

name = input("Name?")
print "your name is %s" % name

why do we use d or what ever, does it make a difference?

Upvotes: 3

Views: 13098

Answers (5)

wim
wim

Reputation: 363476

Others have already given the reason for using %d. I would just point out the following method of string formatting is the new standard in python, and if you're writing new code then syntax using str.format should be preferred to the % formatting:

>>> print "your name is {name}".format(name="Shameer")
your name is Shameer

see http://docs.python.org/library/string.html#formatstrings for more details.

Upvotes: 3

jason
jason

Reputation: 5491

d specifies the variable type for the print function to use. "d" for decimal, "c" for character....

read this

http://docs.python.org/library/functions.html

Upvotes: 1

user206545
user206545

Reputation:

You use %d to print out integers. To print strings, you would use %s.

i = 10
print 'The value is %d' % i
name = "Larry"
print 'My name is %s' % name

Upvotes: 1

dhg
dhg

Reputation: 52701

%d indicates that the value is an integer. %s would be used for strings, which seems better for your example. See here for more information about string formatting in Python: http://docs.python.org/library/stdtypes.html#string-formatting

Upvotes: 3

icktoofay
icktoofay

Reputation: 129139

The d in %d stands for decimal. %d is for formatting numbers. %s is for formatting strings. (thus, the example you gave actually doesn't work) Yes, it matters. You need to tell Python where to place the thing after the % operator into the string.

Upvotes: 4

Related Questions