mikebmassey mikebmassey - 1 month ago 7
Python Question

Formatting negative fixed-length string


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


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


If I wanted to format the string to be:


how could I do this?

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


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)

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