Guy Markman Guy Markman - 16 days ago 7
Python Question

How to use string formating in specific size based variables?

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 creat a loop for it?

Answer

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.
Comments