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))
Answer from moinudin on Stack OverflowHello, so I am starting to learn python on my own learnpython.org and I am currently on the string formatting section and it starts talking about %d and $s. I kinda understand what it does but not really. However my main question is why do we use %s and %d. One example I have seen was
name = 'Geek
print ("Hey, %s,!" % name)
This printed out "Hey, Geek!". But why do we use it when we can also just do
print ("Hey", name)
As I am typing this out I kind of see the use but still any advice would be helpful
Edit: Thanks for all the replies they really helped!! I will be sending in thousands of more questions as I continue to learn.
When using the format specifier "d" within an f-string, you can only input integers. I've seen online that the utility of "d" is to convert a number into a string of decimal digits, but if the specifier can only handle ints, what is it actually doing? For everything ChatGPT says it does, I have inputted the example into Python without the "d", and all outputs remained exactly the same.
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))
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
Argument unpacking seems to be what you're looking for.
**D is used for unpacking arguments. It expands the dictionary into a sequence of keyword assignments, so...
'{say} => {get}'.format(**D)
becomes...
'{say} => {get}'.format(say = 5, get = shrubbery)
The **kwargs trick works because keyword arguments are dictionaries.