Skip to content Skip to sidebar Skip to footer

Printing With Exactly 1 Space If A Single Digit?

I'm printing an integer, that may be 1 or 2 digits long. I'm using : print str(myInt) However, I want it to always print out something that is 2 'spaces' long. As in if myInt is

Solution 1:

>>> print '{:2}'.format(1)
 1
>>> print '{:2}'.format(23)
23

Solution 2:

import re
x=[1,15,20,3]
print [re.sub(r"^0"," ",str(i).zfill(2)) for i  in x]

Output:[' 1', '15', '20', ' 3']

A tough way to do easy things :P


Solution 3:

You can achieve the desired output by doing:

print "%2s" % num

Where 2 is the minimum field width. For example:

print "%2s" % 4
print "%2s" % 12

will result in:

 4
12

If you need more leading spaces you just need to replace the 2 in %2s for the appropriate minimum field width. I recommend you read the String Formatting Operations documentation.


Solution 4:

Here, you don't need to convert Intger to String.

val = 10
val1 = 1
print "%2d" % val
print "%2d" % val1

output:

10
 1

Post a Comment for "Printing With Exactly 1 Space If A Single Digit?"