The "%" operator is used to format a set of variables enclosed in a tuple (a fixed size list), together with a format string.
print ("%d squared is %d" % (10, 10*10))
The % operators in the string are replaced in order by the elements in the tuple.
%d is used for integers, where as %s is used for strings
Eg.
>>>name = "John"
>>>age = 23
>>>print "%s is %d years old." % (name, age)
John is 23 years old.
Answer from user3636636 on Stack Overflow':10d' in f string
d within print statement python
What is the purpose of the format specifier "d"?
python - What does {:d} do? - Stack Overflow
Hello, 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.
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.