Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string formatting: padding negative numbers

I would like to format my integers as strings so that, without the sign, they will be zero-padded to have at least two digits.

For example I want

1
-1
10
-10

to be

01
-01
10
-10

Specifically, I want different minimum string lengths for negative numbers (3) and non-negative numbers (2). Simple number padding as detailed here is insufficient. Is this possible?

like image 465
carmander Avatar asked Oct 23 '25 19:10

carmander


1 Answers

According to here, you need a space before the type descriptor, so both

'% d'%(1)

and

'{: d}'.format(1)

result in (notice the space)

' 1'

aligning nicely with the result of the above called with -1:

'-1'
like image 142
Alex Thomas Avatar answered Oct 25 '25 09:10

Alex Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!