我如何从字符串列表中删除所有额外字符以转换为整数
How can i remove all extra characters from list of strings to convert to ints
大家好,我是编程的新手,Python,这是我的第一个 post,所以对于任何糟糕的形式,我深表歉意。
我正在抓取网站的下载计数,并在尝试将字符串数字列表转换为整数以获取总和时收到以下错误。
ValueError:以 10 为底的 int() 无效文字:'1,015'
我试过 .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)
字符串在 Python 中是不可变的。因此,当您调用 item.replace(",", "")
时,方法 returns 是您想要的,但它没有存储在任何地方(因此不在 item
中)。
编辑:
我建议:
for i in range(len(downloadCount_clean)):
if "," in downloadCount_clean[i]:
downloadCount_clean[i] = downloadCount_clean[i].replace(",", "")
第二次编辑:
为了更简单一点 and/or 优雅 :
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 规则:)
大家好,我是编程的新手,Python,这是我的第一个 post,所以对于任何糟糕的形式,我深表歉意。
我正在抓取网站的下载计数,并在尝试将字符串数字列表转换为整数以获取总和时收到以下错误。 ValueError:以 10 为底的 int() 无效文字:'1,015'
我试过 .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)
字符串在 Python 中是不可变的。因此,当您调用 item.replace(",", "")
时,方法 returns 是您想要的,但它没有存储在任何地方(因此不在 item
中)。
编辑:
我建议:
for i in range(len(downloadCount_clean)):
if "," in downloadCount_clean[i]:
downloadCount_clean[i] = downloadCount_clean[i].replace(",", "")
第二次编辑:
为了更简单一点 and/or 优雅 :
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 规则:)