简体   繁体   English

从python中的列表元素中删除字符

[英]removing characters from list elements in python

I am extracting content with the help of scrapy into an array. 我正在借助scrapy将内容提取到数组中。 Each element has the unwanted characters ": " inside which I would like to remove as efficient as possible. 每个元素都有多余的字符“:”,我想在其中尽可能高效地删除它们。

v = response.xpath('//div[@id="tab"]/text()').extract()
>>> v
['Marke:', 'Modell:']
>>> for i in v : re.sub(r'[^\w]', '', i)
... 
'Marke'
'Modell'

Now that seems to work, but how can I retain the result? 现在看来可行,但是我如何保留结果呢? In my code, v hasn't changed: 在我的代码中, v没有改变:

>>> v
['Marke:', 'Modell:']

You can solve this with a list comprehension : 您可以使用列表理解来解决此问题:

>>> v = response.xpath('//div[@id="tab"]/text()').extract()
>>>
>>> import re
>>> v = [re.sub(r'[^\w]', '', i) for i in v]
>>> v
['Marke', 'Modell']

I think that pulling in regex for this is a little overkill: use the string replace method: 我认为为此引入regex有点矫kill过正:使用字符串replace方法:

v = ['Marke:', 'Modell:']
v = [str.replace(':', '') for str in v]
print(v)

Output: 输出:

['Marke', 'Modell']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM