簡體   English   中英

我如何從字符串列表中刪除所有多余的字符以轉換為整數

[英]How can i remove all extra characters from list of strings to convert to ints

嗨,我是編程和Python的新手,這是我的第一篇文章,對於任何不良形式,我深表歉意。

我正在抓取網站的下載計數,並在嘗試將字符串數字列表轉換為整數以獲取總和時收到以下錯誤。 ValueError:以10為底的int()的無效文字:'1,015'

我已經嘗試過.replace(),但是它似乎沒有做任何事情。

並嘗試構建一個if語句以從包含逗號的任何字符串中刪除逗號: Python是否有一個包含子字符串方法的字符串?

這是我的代碼:

    downloadCount = pageHTML.xpath('//li[@class="download"]/text()')
    downloadCount_clean = []

    for download in downloadCount:
        downloadCount_clean.append(str.strip(download))

    for item in downloadCount_clean:
        if "," in item:
            item.replace(",", "")
    print(downloadCount_clean)

    downloadCount_clean = map(int, downloadCount_clean)
    total = sum(downloadCount_clean)

字符串在Python中不可變。 因此,當您調用item.replace(",", "") ,該方法將返回您想要的內容,但是它不會存儲在任何地方(因此不在item )。

編輯:

我建議這樣:

for i in range(len(downloadCount_clean)):
    if "," in downloadCount_clean[i]:
        downloadCount_clean[i] = downloadCount_clean[i].replace(",", "")

第二編輯:

為了更加簡單和/或優雅:

for index,value in enumerate(downloadCount_clean):
    downloadCount_clean[index] = int(value.replace(",", ""))

為簡單起見:

>>> aList = ["abc", "42", "1,423", "def"]
>>> bList = []
>>> for i in aList:
...     bList.append(i.replace(',',''))
... 
>>> bList
['abc', '42', '1423', 'def']

或僅使用一個列表:

>>> aList = ["abc", "42", "1,423", "def"]
>>> for i, x in enumerate(aList):
...     aList[i]=(x.replace(',',''))
... 
>>> aList
['abc', '42', '1423', 'def']

不知道這是否違反任何python規則:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM