S
Steven D'Aprano
Problem: I have an application where I need to print integers differently
depending on whether they are positive or negative. To be more specific, I
have to print something that looks like:
"something + 1"
"something - 1"
Note the space between the sign and the number. If I didn't need that
space, I would have no problem. Yes, I do need that space.
I build the format string on the fly, then pass it to another function
which actually fills in the values. Simplified example:
def format(n):
if n > 0:
return "something positive + %(argument)d"
# real code has a good half-dozen named keys
elif n < 0:
return "something negative - %(argument)d"
else:
return "blank"
def display(**kwargs):
fs = format(kwargs['argument'])
return fs % kwargs
This works fine for positive and zero values:
'something positive + 1'
but not for negative, due to the extra negative sign:
'something negative - -1'
Are there any string formatting codes that will place a space between the
sign and the number?
depending on whether they are positive or negative. To be more specific, I
have to print something that looks like:
"something + 1"
"something - 1"
Note the space between the sign and the number. If I didn't need that
space, I would have no problem. Yes, I do need that space.
I build the format string on the fly, then pass it to another function
which actually fills in the values. Simplified example:
def format(n):
if n > 0:
return "something positive + %(argument)d"
# real code has a good half-dozen named keys
elif n < 0:
return "something negative - %(argument)d"
else:
return "blank"
def display(**kwargs):
fs = format(kwargs['argument'])
return fs % kwargs
This works fine for positive and zero values:
'something positive + 1'
but not for negative, due to the extra negative sign:
'something negative - -1'
Are there any string formatting codes that will place a space between the
sign and the number?