如何从字符串列表中删除所有额外字符以转​​换为整数 [英] How can i remove all extra characters from list of strings to convert to ints

查看:89
本文介绍了如何从字符串列表中删除所有额外字符以转​​换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程和 Python 还很陌生,这是我的第一篇文章,所以对于任何糟糕的形式,我深表歉意.

Hi I'm pretty new to programming and Python, and this is my first post, so I apologize for any poor form.

我正在抓取网站的下载计数,并在尝试将字符串数字列表转换为整数以获取总和时收到以下错误.ValueError:int() 的文字无效,基数为 10:'1,015'

I am scraping a website's download counts and am receiving the following error when attempting to convert the list of string numbers to integers to get the sum. ValueError: invalid literal for int() with base 10: '1,015'

我尝试过 .replace() 但它似乎没有做任何事情.

I have tried .replace() but it does not seem to be doing anything.

并尝试构建一个 if 语句以从包含逗号的任何字符串中取出逗号:Python有字符串包含子字符串的方法吗?

And tried to build an if statement to take the commas out of any string that contains them: 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)

推荐答案

字符串在 Python 中不可变.因此,当您调用 item.replace(",", "") 时,该方法会返回您想要的内容,但它不会存储在任何地方(因此不在 item 中).

Strings are not mutable in Python. So when you call item.replace(",", ""), the method returns what you want, but it is not stored anywhere (thus not in item).

我建议:

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

第二次

为了更简单和/或优雅:

For a bit more simplicity and/or elegance :

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

这篇关于如何从字符串列表中删除所有额外字符以转​​换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆