mikebmassey
mikebmassey

Reputation: 8594

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.

Upvotes: 2

Views: 1210

Answers (3)

Paul S
Paul S

Reputation: 21

If you can convert the string to a float, you can do this:

>>> '{:0=10.4f}'.format(float('-10.0040'))
'-0010.0040'
>>> '{:0=10.4f}'.format(float('10.0040'))
'00010.0040'

Upvotes: 2

wim
wim

Reputation: 363243

I don't know how to do it with str.format. May I propose using str.zfill instead?

>>> '-10.0040'.zfill(10)
'-0010.0040'
>>> '10.0040'.zfill(10)
'00010.0040'

If you can bear converting to a number before formatting:

>>> from decimal import Decimal
>>> '{:010.4f}'.format(Decimal('10.0040'))
'00010.0040'
>>> '{:010.4f}'.format(Decimal('-10.0040'))
'-0010.0040'

Upvotes: 4

Brendan Abel
Brendan Abel

Reputation: 37549

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

Upvotes: 5

Related Questions