Home > Software engineering >  Transform string to integer/float/numeric not working Python
Transform string to integer/float/numeric not working Python

Time:02-06

I have a string i = '0, 1, 1, 0, 1, 1' For some reason I cannot turn it into a numeric/float/integer.

Depending on the way I try it, I get errors like:

AttributeError: 'str' object has no attribute 'to_numeric'

AttributeError: 'str' object has no attribute 'astype'

could not convert string to float: '0, 1, 1, 0, 1, 1'

Are there any other possibilities to turn a string with numbers into a numerical type?

Thank you very much!

CodePudding user response:

You can convert a string into a list of integers by first splitting the string into a list. Next, use list comprehension to convert each string item into an integer.

s = '0, 1, 1, 0, 1, 1'

l = [int(v) for v in s.split(", ")]
print(l)

Output:

[0, 1, 1, 0, 1, 1]
  • Related