[英]How to use Python to ensure a string is only numbers and then convert it to an integer
[英]How can i convert to integer numbers from string numbers in python
我想更改類型我的字符串編號。 我想讓它們 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)
我收到這樣的錯誤
ns[i]=int(ns[i])
ValueError: invalid literal for int() with base 10: '4,'
當您拆分字符串時,它會被空格拆分...因此每個數字仍然有逗號。
固定的:
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])
問題是split()
使用空格作為默認的拆分字符。 所以還剩下逗號。 您可以使用split(', ')
為 function 指定分隔符。
請參閱此示例,了解如何使用拆分。
您可以在 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)
你可以做
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)
要么
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)
這會將數字列表中的所有數字轉換為整數。 Output
[4, 5, 29, 54, 4, 0, -214, 542, -64, 1, -3, 6, -6]
你犯了一個錯誤。
改變這一行
ns=numbers.split()
進入這個
ns=numbers.split(", ")
當您嘗試將數組的元素轉換為整數時,使用.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'
>>>
相反,你只能做
numbers.split(",")
它會給你正確的 integer 數組。 然后根據您的目的將元素類型轉換為 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.