[英]How can i convert to integer numbers from string numbers in python
I want to change type my string numbers.我想更改类型我的字符串编号。 I wanna make them integer for comparing them which one is bigger.
我想让它们 integer 比较它们哪个更大。
numbers="4, 5, 29, 54, 4 ,0 ,-214, 542, -64, 1 ,-3, 6, -6"
ns=numbers.split()
nsi=[]
for i in range(len(ns)):
ns[i]=int(ns[i])
nsi.append(ns[i])
print(nsi)
I am getting error like this我收到这样的错误
ns[i]=int(ns[i])
ValueError: invalid literal for int() with base 10: '4,'
When you split the string it is split by whitespace... so with each number there is still the comma.当您拆分字符串时,它会被空格拆分...因此每个数字仍然有逗号。
fixed:固定的:
numbers="4, 5, 29, 54, 4 ,0 ,-214, 542, -64, 1 ,-3, 6, -6"
ns=numbers.replace(",", "").split()
nsi=[]
for i in range(len(ns)):
ns[i]=int(ns[i])
nsi.append(ns[i])
print(nsi)
ns[i]=int(ns[i])
You can use different separator in split().您可以在 split() 中使用不同的分隔符。
numbers="4, 5, 29, 54, 4 ,0 ,-214, 542, -64, 1 ,-3, 6, -6"
ns=numbers.split(sep=",")
nsi=[]
for i in range(len(ns)):
ns[i]=int(ns[i])
nsi.append(ns[i])
print(nsi)
You can do你可以做
numbers="4, 5, 29, 54, 4 ,0 ,-214, 542, -64, 1 ,-3, 6, -6"
ns = [int(i) for i in numbers.split(",")]
nsi=[]
for i in range(len(ns)):
nsi.append(ns[i])
print(nsi)
or要么
numbers="4, 5, 29, 54, 4 ,0 ,-214, 542, -64, 1 ,-3, 6, -6"
ns = [int(i) for i in numbers.split(",")]
nsi=[]
nsi.extend(ns)
print(nsi)
That will cast all numbers in numbers list comperation to int's.这会将数字列表中的所有数字转换为整数。 Output
Output
[4, 5, 29, 54, 4, 0, -214, 542, -64, 1, -3, 6, -6]
You made a mistake.你犯了一个错误。
Change this line改变这一行
ns=numbers.split()
Into this进入这个
ns=numbers.split(", ")
Using .split(", ")
will give you an error when you try to convert the elements of the array into integers as numbers.split(", ") will give output as当您尝试将数组的元素转换为整数时,使用
.split(", ")
会给您一个错误。split(", ") 将给出 output 作为
ns = numbers.split(", ")
>>> print ns
['4', '5', '29', '54', '4 ,0 ,-214', '542', '-64', '1 ,-3', '6', '-6'] //'4 ->incorrect output
>>> print int(ns[4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4 ,0 ,-214'
>>>
Instead you can do only相反,你只能做
numbers.split(",")
and it will give you the correct integer array.它会给你正确的 integer 数组。 then typecast the elements for your purpose as int(...)
然后根据您的目的将元素类型转换为 int(...)
>>> ns = numbers.split(",")
>>> print ns
['4', ' 5', ' 29', ' 54', ' 4 ', '0 ', '-214', ' 542', ' -64', ' 1 ', '-3', ' 6', ' -6']
>>> a = int(ns[1])
>>> print a
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.