0

I want to convert string list in int list in python3.x

b = ["1.22","1.45","1.85","2.35","3.73","5.44"]
c= [int(i) for i in b]
print(c)

But I am getting the error

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

What is the error in syntax or possible other solution?

3 Answers3

3

1.22 is not an integer. Use decimal.Decimal('1.23') or float('1.23') instead.

Bill Lynch
  • 76,897
  • 15
  • 123
  • 168
2

These are floats not ints, that's why you get the error, you could modify your code as such:

b = ["1.22","1.45","1.85","2.35","3.73","5.44"]
c = [float(i) for i in b]
print(c)
solid.py
  • 2,794
  • 5
  • 24
  • 30
2

Try first converting to floating point, then convert those floats to ints:

b = ["1.22","1.45","1.85","2.35","3.73","5.44"]
c = [int(float(i)) for i in b]
print(c)

This prints:

[1, 1, 1, 2, 3, 5]
Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318