2

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?

1
  • copying the headline into google, first hit, then search for padd, leads to rjust, use as num_digits = 5; print str(12).rjust(num_digits,'0') Commented Mar 26, 2012 at 6:49

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.