How can I format the string according to its length at runtime?

Skip Montanaro skip at pobox.com
Wed Jun 20 00:16:24 CEST 2001


    ed> I am trying to supply the precision formating at run time:
    ed> s = 123
    ed> print '(0x%-6X -)'%s

    ed> where I try to dynamically supply the number 6 from (6- length of s), 
    ed> I can't find a way to dynamically supply that. 

Check here:

    http://www.python.org/doc/current/lib/typesseq-strings.html

Basically, you put * where you want to interpolate the width from a number:

    >>> wid = 12
    >>> print '(0x%*s)' % (wid, "allan")
    (0x       allan)

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list