difference between %s and %d

Ethan Furman ethan at stoneleaf.us
Fri Oct 1 15:51:27 EDT 2010


Ethan Furman wrote:
> If I'm printing the number 735, or any other positive or negative 
> integer, is there any difference between %7s and %7d?

Grant Edwards wrote:
 > Let's ask Python:
 >
 >   --> [n for n in range(-99999999,99999999,123) if ("%7d" % n)
 >           != ("%7s" % n)]
 >   []
 >
 >   --> [n for n in range(-99999,99999) if ("%7d" % n) != ("%7s" % n)]
 >   []
 >
 > Apparently not.

MRAB wrote:
 > "%s" uses str(). In Python 2.7:
 >
 >  --> class MyInt(int):
 > ...     def __init__(self, value):
 > ...         int.__init__(self, value)
 > ...     def __str__(self):
 > ...         return "MyInt(%d)" % self
 > ...
 >  --> MyInt(735)
 > 735
 >  --> "%7d" % MyInt(735)
 > '    735'
 >  --> "%7s" % MyInt(735)
 > 'MyInt(735)'


Thanks!  Both enlightening answers.

~Ethan~



More information about the Python-list mailing list