python string format with negative sign for negative number, but space for positive number

Viewed 2237

Is there a format code to format -2.34 as '-2.3', but +2.34 as ' 2.3' (notice the leading space)? Basically show the negative sign but leave a space for positive sign.

4 Answers

Use " " (a space) to insert a space before positive numbers and a minus sign before negative numbers:

txt = "The temperature is between {: } and {: } degrees celsius."

print(txt.format(-3, 7))

answer :

The temperature is between -3 and  7 degrees celsius. 

You can try format on float:

>>> "{: .1f}".format(+2.34)
' 2.3'
>>> "{: .1f}".format(-2.34)
'-2.3'

Using f strings it can be done very succintly:

MYSTR = 2.34
print(f'{MYSTR:{".1f" if MYSTR < 0 else " .1f"}}')
f = lambda i: " %.1f"%i if i > 0 else "%.1f"%i

pos = 2.358
neg = -2.358

print(f(pos)) # " 2.3"
print(f(neg)) # "-2.3"
Related