Reputation: 189
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
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
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
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
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
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