3

My Python code was doing something strange to me (or my numbers, rather):

a)

float(poverb.tangibles[1])*1000
1038277000.0

b)

float(poverb.tangibles[1]*1000)
inf

Which led to discovering that:

long(poverb.tangibles[1]*1000)

produces the largest number I've ever seen.

Uhhh, I didn't read the whole Python tutorial or it's doc. Did I miss something critical about how float works?

EDIT:

>>> poverb.tangibles[1]
u'1038277'
2
  • 6
    This question would be far easier to answer if you give us the value of poverb.tangibles[1] Commented Aug 10, 2012 at 7:35
  • +1 for constructive feedback. best. site. ever. Commented Aug 10, 2012 at 7:37

1 Answer 1

17

What you probably missed is docs on how multiplication works on strings. Your tangibles list contains strings. tangibles[1] is a string. tangibles[1]*1000 is that string repeated 1000 times. Calling float or long on that string interprets it as a number, creating a huge number. If you instead do float(tangibles[1]), you only get the actual number, not the number repeated 1000 times.

What you are seeing is just the same as what goes on in this example:

>>> x = '1'
>>> x
'1'
>>> x*10
'1111111111'
>>> float(x)
1.0
>>> float(x*10)
1111111111.0
Sign up to request clarification or add additional context in comments.

1 Comment

Yah, string "multiplication" does tend to surprise but since it is actually sequence multiplication (where strings are a kind of sequence) it's part of the language and ain't going away. Along those lines, string % integer also isn't what you might guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.