将字符串转换为整数/浮点数/数字在Python中无法正常工作。

huangapple go评论67阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2023年2月6日 04:50:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定