1

I know that when I use

"%2d"%(x)

I will get a string of x and in at least size of 2, and if the length of x is shorter than 2 I will get spaces before it. But how can I give the 2 as a variable too? For example:

"%nd"%(2,1)
' 1'

Is it possible in Python? Or do I need to create a loop for it?

3
  • 3
    '%*d' % (n, x) should work Commented Nov 17, 2016 at 17:13
  • @vaultah is right. It is working for me. Commented Nov 17, 2016 at 17:15
  • FWIW the new formatting should work in Python 2.7: '{:>{}}'.format(x, n) Commented Nov 17, 2016 at 17:19

2 Answers 2

1

Use * and the actual width will be read from the next element of the tuple of values, and the value to convert will be the one following:

>>> "%*d" % (2, 1)
' 1'

This is documented in the String Formatting Operations section of the documentation — it says:

  1. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! This is what @vaultah commented an this works!
1

You could choose to be more verbose with the new style formatting:

>>> '{:{width}d}'.format(1, width=2)
' 1'

1 Comment

@guy: Actually the new style is a bit more powerful (and easy, once you get the hang of it), so I suggest you take or make the time to learn it.

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.