Something peculiar with the % sign


#1

In this piece of code:

print "There are %d items in the suitcase." % (list_length)

we see the "%" sign in use. In this case it is "%d".

I've noticed that only a couple "%-letter" combinations actually work.
"%s, %d, %u, %o and %r" for example, all return the same result, but "%a, %b, %w or %l" just return an error.

There's even a special combination, namely, "%f" which returns a float (same result as %s or %d, but with an added decimal point followed by a couple of zeroes).
There's also %c,which doesn't return an error, but doesn't return the answer either. (e.g. it leaves a blank)

My question(s):
- Can someone explain to me how the %s, %d and other combinations work?
- Why so many combinations that do the exact same thing, wouldn't just %s or just %d suffice?
- Also: are the %f and %c special or something?

Thanks in advance!


#2

I can't explain it in any detail, but this will give you some information on the various formatting types until someone else comes along who can. :smile:
https://docs.python.org/2/library/stdtypes.html#string-formatting-operations