Yasser
Yasser

Reputation: 1808

How to specify string padding with a variable in Python 2.5?

For example:

print('items %05d'%12)

would print 00012.

Can the amount of padding be specified by a variable instead of a literal? I believe python 2.6+ has the .format function but what are the options with python 2.5?

Upvotes: 2

Views: 741

Answers (3)

MarkHu
MarkHu

Reputation: 1859

For more modern versions of Python 3.x try this:

python -c 'print(f"{2**32:,}".rjust(16))'
   4,294,967,296

Upvotes: 0

steveha
steveha

Reputation: 76725

You can replace the width number with a * and the Python % substitution will expect an integer value, and use that for the width. Since you will now have at least two values for the % operator (one width and one actual value) you will need to make a tuple to pass them together.

print "items %0*d" % (5, 12)

If you leave out the 0 before the * you will get padding with spaces rather than 0.

Documented here:

http://docs.python.org/release/2.5.2/lib/typesseq-strings.html

Section 3.6.2, rule 4.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799014

>>> '##%*s##' % (3, '$')
'##  $##'

Upvotes: 1

Related Questions