[Tutor] combine string and integer

alan.gauld@bt.com alan.gauld@bt.com
Thu, 23 May 2002 13:02:22 +0100


> I have two variables that I want to merge into one based on a 
> condition:
> 
>     def amount(self):
>         if amount > 0:
>             amount = amount
>         else:
>             amount = amount, '-'
> (or amount = amount * (-1), '-')

But since you have a self in there I assume this is a method
rather than a vanilla function and amount is an attribute?

In which case it needs self in front.
BUT having a method and attribute with the same name is a bad 
idea so rename one and make it thus:

     def amount(self):
         if self.amt < 0: self.amt *= -1
         return self.amt

Which gets the modulus(size) of amount.
But thats not really what you want....

> function to remove the - in front of 25, and put it behind it, 25-.

If amount is an integer you can't do that. Where the '-' appears 
is a presentation issue that you should solve in your printing code.
Python stores the number as a number not a string.


> I assume amount[1:9] can remove the - in front? Or does the 
> slice notation only work on strings? 

No it works on any sequence type. But numbers are not sequences.
However str(amount)[1:9] will indeed strip the first character.
But you need to make sure the number is left justified. Using 
the format operator (%) will do this for you.

> However, the main problem is to get the - to go behind the 
> amount. 

Thats a display issue. Try something like this:

def mod(n):
   if n < 0: n *= -1
   return n

if amt < 0: s = "%d-" % mod(amt)      
else: s = "%d" % amt

print s

> suppose? However, I want 25- or 25.0-. 

Since its money you probably want to force two deciomal places
too which you can do by using the format characters. See the 
documentation for the details under %f...

Or look at the simple sequences page of my tutor for 
more info. And the Raw Data page for more about Python 
data types.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld