Transform string to integer/float/numeric not working Python

Question:

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!

Asked By: Ang

||

Answers:

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]
Answered By: CodeMonkey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.