% string formatting - what special method is used for %d?
steve+python at pearwood.info
Sat Dec 10 03:52:02 EST 2016
On Sat, 10 Dec 2016 06:06 pm, Veek M wrote:
> When we do:
> print '%s %d' % ('hello', 10)
> what special method is being invoked internally within the string-
%d requires the argument to be an int, or able to be converted to int using
the __int__ special method.
py> class X(object):
... def __int__(self):
... return 42
py> "%d" % X()
> format() invokes format__
> print invokes __str__
print actually invokes __str__ or __repr__, whichever is available.
> I'm basically trying to make sense of:
> raise TypeError('urkle urkle %s' % list(dictionary))
> <=> raise TypeError('urkle urkle %s' % [ key1, val1, key2, val2 ]
The raise TypeError part of the code is irrelevant to your question. You
should always simplify your code to only the part that is relevant.
behaves the same regardless of how some_string is made.
> So, the % operator reads the format specifier and notices %s and
> therefore calls __str__ in the list class to figure out how to represent
> [ key1, val1, key2, val2 ].
> However what if I use %d? How do the other format specs work?
The format specifiers are similar to these:
%s => str(obj), which ends up calling __str__ or __repr__
%r => repr(obj), which ends up calling __repr__ or __str__
%c => chr(obj), or obj must be a string of length 1
%d %i %u => int(obj), which ends up calling __int__
%x %X => int(obj), then convert to hexadecimal
%o => int(obj), then convert to octal
%e %E %f %g %G => float(obj), which ends up calling __float__
%% => a literal % sign
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list