Search code examples
pythonformatalignmentpython-3.5number-formatting

python3.5 format number and align in one line


Is there a way to combine number formatting and aligning in the same format line?

for example, I'm trying to show a percentage with only 2 decimals and align to the right in a given space. The two lines approach works fine:

value = '{:05.2f}%'.format(3.141592653589793)
print('{:>{width}}'.format(value, width=20))

But is there a way to do it in one line? something like this:

print('{:05.2f>{width}}%'.format(3.141592653589793, width=20))

Solution

  • Answers the letter, if not the spirit, of the question:

    print('{:>{width}}'.format('{:05.2f}%'.format(3.141592653589793), width=20))