By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,364 Members | 1,536 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,364 IT Pros & Developers. It's quick & easy.

Negative integers and string formating

P: n/a
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:
>>display(argument=0)
'blank'
>>display(argument=1)
'something positive + 1'

but not for negative, due to the extra negative sign:
>>display(argument=-1)
'something negative - -1'

Are there any string formatting codes that will place a space between the
sign and the number?

--
Steven

Oct 24 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Steven D'Aprano wrote:
Are there any string formatting codes that will place a space between the
sign and the number?
Not that I know of, why not use the absolute value (after checking if
it is negative),

In [1]: abs(-1)
Out[1]: 1

Oct 24 '06 #2

P: n/a
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrites:
def display(**kwargs):
fs = format(kwargs['argument'])
return fs % kwargs
def display(**kwargs):
fs = format(kwargs['argument'])
return fs % dict((x, abs(y)) for x,y in kwargs.iteritems())
Oct 24 '06 #3

P: n/a
On Mon, 23 Oct 2006 18:56:21 -0700, Paul Rubin wrote:
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrites:
>def display(**kwargs):
fs = format(kwargs['argument'])
return fs % kwargs

def display(**kwargs):
fs = format(kwargs['argument'])
return fs % dict((x, abs(y)) for x,y in kwargs.iteritems())
That will do it! Thanks,

--
Steven

Oct 24 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.