Engine
Engine

Reputation: 5422

Force casting to int in python

I have a list of values that I have to use asint:

ValueError                                Traceback (most recent call last)
<ipython-input-4-9b4decbf862c> in <module>()
      1 for i in range(len(Training_Raw)-1):
----> 2     print(int(Training_Raw[row_indeces[i]][-1]))

ValueError: invalid literal for int() with base 10: '5.0'

As you can see trying to convert them to int through the error message, despite a "valid" values.

Does anybody here has a hint how to solve this ?

Upvotes: 0

Views: 5777

Answers (2)

yeniv
yeniv

Reputation: 1639

The sting is a float value so it first has to be converted to a float and then to int. This should work:

int(float(value))

Upvotes: 2

kchomski
kchomski

Reputation: 3010

It's because Python expects "integer strings" in this case, e.g. '5' instead of '5.0'. One solution is to cast to float first and then to int:

>>> int(float('5.0'))
5

Upvotes: 2

Related Questions