英文:
Transform string to integer/float/numeric not working Python
问题
我有一个字符串i = '0, 1, 1, 0, 1, 1'
由于某种原因,我无法将其转换为数字/浮点数/整数。
根据我尝试的方式不同,我会遇到错误,如:
AttributeError: 'str' object has no attribute 'to_numeric'
AttributeError: 'str' object has no attribute 'astype'
无法将字符串转换为浮点数:'0, 1, 1, 0, 1, 1'
是否有其他可能将包含数字的字符串转换为数值类型?
非常感谢!
英文:
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!
答案1
得分: 0
你可以通过首先将字符串拆分为列表,然后使用列表推导将每个字符串项转换为整数,将字符串转换为整数列表。
s = '0, 1, 1, 0, 1, 1'
l = [int(v) for v in s.split(", ")]
print(l)
输出:
[0, 1, 1, 0, 1, 1]
英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论