mikebmassey mikebmassey - 2 months ago 16
Python Question

Formatting negative fixed-length string

In

python
, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:

'{:0>10}'.format('10.0040')
'00010.0040'


I have a negative number and want to express the negative, I would get this:

'{:0>10}'.format('-10.0040')
'00-10.0040'


If I wanted to format the string to be:

'-0010.0040'


how could I do this?

I could do an if/then, but wondering if format would handle this already.

Answer

You're problem is that your "number" is being represented as a string, so python has no way of knowing whether it's positive or negative, because it doesn't know it's a number.

>>> '{: 010.4f}'.format(10.0400)
' 0010.0400'
>>> '{: 010.4f}'.format(-10.0400)
'-0010.0400'

This fills with 0's and has a fixed precision. It will use a space for positive numbers and a - for negative.

You can change the behavior (i.e. + for positive signs, or just fill with an extra 0) using the sign portion of the formatting token

Comments