如何从要转换为整数的字符串列表中删除所有额外字符

2024-10-16 17:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我对编程和Python还很陌生,这是我的第一篇文章,所以我为任何糟糕的形式道歉。你知道吗

我刮一个网站的下载计数,并收到以下错误时,试图将字符串数字列表转换为整数,以获得总和。 ValueError:基数为10的int()的文本无效:“1015”

我尝试过.replace(),但它似乎没有任何作用。你知道吗

并尝试构建一个if语句,从包含它们的任何字符串中去掉逗号: Does Python have a string contains substring method?

这是我的密码:

    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)

Tags: 字符串incleanforif网站download编程
2条回答

为了简单起见:

>>> 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规则:)

字符串在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(",", ""))

相关问题 更多 >