user200783
user200783

Reputation: 14346

Python str.format - Get (only) the sign of a number?

Using Python's str.format method, is there a format string which will extract only the sign of a numeric argument?

More specifically, I need to be able to print the sign and the rest of the numeric argument separately in order to insert a character between them. This may be a space (e.g. turning a -4 into a - 4) or a custom base prefix, (e.g. $ for hexadecimal: -$02).

Upvotes: 2

Views: 277

Answers (2)

AChampion
AChampion

Reputation: 30288

This is purely for reference, digging deep into the format function you can do it just with formatting:

def myformat(n, base):
    fill = {'d': ' ', 'x': '$'}
    return "{:{f}=+{d}{b}}".format(n, b=base, f=fill[base], d=len(format(n, "+"+base))+1)

>>> print(myformat(100, 'd'))
+ 100
>>> print(myformat(100, 'x'))
+$64
>>> print(myformat(-100, 'x')
-$64

The explanation:

n = number
f = fill character
= = pad after sign
+ = show sign
d = number of digits to pad to (number of digits of n with sign + 1 for pad char)
b = integer base

Upvotes: 0

Daniel
Daniel

Reputation: 42778

No, there is no special format string. You have to write it yourself:

"{0}${1:02d}".format('+-'[s<0], abs(s))

Upvotes: 3

Related Questions