[Tutor] Strings and the % Operator

Skip Montanaro skip@mojam.com (Skip Montanaro)
Thu, 16 Dec 1999 11:20:15 -0600 (CST)

    >>> myString = "A bunch of stuff that exceeds 10 characters"
    >>> otherString = "or not!"
    >>> new1 = "[1: %-10s ]" % myString
    >>> new1
    '[1: A bunch of stuff that exceeds 10 characters ]'
    >>> new2 = "[1: %-10s ]" % otherString
    >>> new2
    '[1: or not!    ]'

    Doug> The second case does exactly what I want, but the first doesn't
    Doug> truncate.

Th %-10s doesn't truncate.  It will only pad.  If you want it truncated,
you're going to have to add a precision specifier as Michael described or
truncate the string:

    >>> import string
    >>> "<%-5s>" % string.digits 
    >>> "<%-5.5s>" % string.digits 
    >>> "<%-5s>" % string.digits[0:5]

I suspect this might not be very intuitive, but it does match the behavior
of C's printf family of functions, from which it's derived.  On my Linux
system, the printf man page states:

    In no case does a non-existent or small field width cause truncation of
    a field; if the result of a conversion is wider than the field width,
    the field is expanded to contain the conversion result.


Skip Montanaro | http://www.mojam.com/
skip@mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...