Question

I know that in Python, to align a string within a certain width, one can use a format string. For example, the following code prints the centered the string 'Readability counts' at 30 spaces wide:

print "{0: ^30}".format("Readability counts")

Now I would like to center the string "2 + 4", but I'd like to build it up out of two attributes of the same object (obj.atr1 and obj.atr2).

I could first combine the two values to form one string (either using concatenation or formatting) and then pass that one on to the next format string, but I was wondering if there was a more elegant way of dealing with this. Preferably, I'd use just one format operation, as this would allow me to just pass obj as an argument and get the attributes out using the format string. Something along the lines of the following..

print "{0.atr1} + {0.atr2}".format(obj)

.. but then with centering added to it.

I know it works when I do something like this..

print "{0: ^30}".format("{0.atr1} + {0.atr2}".format(obj))

.. but that is quite inconvenient if I were to want to use other attributes of obj in the leftmost format strings.

Was it helpful?

Solution

Your last approach seems sensible, you still can use other obj attributes passing it once again:

print "{0: ^30} | {1.atr3}".format("{0.atr1} + {0.atr2}".format(obj), obj)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top