[Tutor] calculation in string operations

Alan Gauld alan.gauld at btinternet.com
Thu Aug 4 02:20:42 CEST 2011


On 04/08/11 00:16, David wrote:

> After all, my_weight is a number that can be multiplied by a float.
> I would expect Python to evaluate the expression after the (final)
> operator and then having it inserted into the string.

But it doesn't because the % format operator has a higher precedence.
So it sees the line as

(string % value) * number

But you want

string % (value * number)

So you need parens to force it to see things your way.

> print "My weight in pounds is %d"  % my_weight * 2.20462262
>
> python weight.py
> Traceback (most recent call last):
>    File "weight.py", line 4, in<module>
>      print "My weight in pounds is %d"  % my_weight * 2.20462262
> TypeError: can't multiply sequence by non-int of type 'float'

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/






More information about the Tutor mailing list