'Python conditional format

I want to avoid the code that follows. I need to format one integer in a way that it takes his deserved place. Probably I could explain it better. I do not know. But it needs a very short look at that piece of code to understand what do I want to do. It is very simple.


if   a > 9999999: print('{:08d}'.format(a))
elif a > 999999: print('{:07d}'.format(a))
elif a > 99999: print('{:06d}'.format(a))
elif a > 9999: print('{:05d}'.format(a))
elif a > 999: print('{:04d}'.format(a))
elif a > 99: print('{:03d}'.format(a))
elif a > 9: print('{:02d}'.format(a))
else:      print('{:01d}'.format(a))

This works, but I guess there is a better way to do the same. Thank you in advance...



Solution 1:[1]

You want to print a number with as much space as… it takes… to print it…?! That's what happens when you simply print the number:

>>> a = 123456789
>>> print(a)
123456789
>>> a = 1
>>> print(a)
1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 deceze