我想在一个replace函数中用空格替换多个字符串

2024-05-23 14:23:54 发布

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

我想用空白代替字符串。对于下面的脚本,它可以工作,但当我有多个不同的字符串字符串,以重放它与空白,我会被绊倒。你知道吗

例如:(我使用xpath etxtract获取字符串列表,假设8个字符串相同,3个字符串相同,2个字符串相同,…)

links = [ 'ABCDEFGH google', 'ABCDEFGH google', 'Samsung mobile',  
'ABCDEFGH serachgoogle google', 'ABCDEFGH google',  'XYZacbxf 
12153131' , 'Samsung mobile', 'Apple smartphone x10',.............]

m = []
for link in links:
    temp = link.replace("ABCD", '')
    m.append(temp)

(在上面,我首先用空格替换'ABCD',然后用空格替换'ABCD',最后用空格替换'mobile',在一个replce函数中用空格替换最多20+个差异字符串) )不知道有没有可能!,有人对此有想法,请帮助。) (提前谢谢!)你知道吗

已尝试=>

m = []
for link in links:
    temp = link.replace("ABCD", '' or "mobile", '' or "google", 
'' or ...........upto available replacing string) 
    m.append(temp)

Tags: or字符串inforgooglelinklinksmobile
3条回答

不需要使用额外的列表,就可以使用regex替换列表中每个元素中不必要的字符串。你知道吗

正则表达式看起来像:

re.sub(r'ABCD|mobile', '', x)

代码

import re

links = [ 'ABCDEFGH google', 'ABCDEFGH google', 'Samsung mobile',  'ABCDEFGH serachgoogle google', 'ABCDEFGH google',  'XYZacbxf 12153131' , 'Samsung mobile', 'Apple smartphone x10']

res = []
for x in links:
    res.append(re.sub(r'ABCD|mobile', '', x))

print(res)
# ['EFGH google', 'EFGH google', 'Samsung ', 'EFGH serachgoogle google', 'EFGH google', 'XYZacbxf 12153131', 'Samsung ', 'Apple smartphone x10']

您应该使用与要替换的所有术语匹配的正则表达式:

import re

links = ['ABCDEFGH google', 'ABCDEFGH google', 'Samsung mobile',  
'ABCDEFGH serachgoogle google', 'ABCDEFGH google',  'XYZacbxf',
'12153131' , 'Samsung mobile', 'Apple smartphone x10']

to_replace = ['ABCD', 'mobile', 'google']
regex = re.compile('|'.join(to_replace))

new_links = [re.sub(regex, '', link) for link in links]
print(new_links)

输出:

['EFGH ', 'EFGH ', 'Samsung ', 'EFGH serach ', 'EFGH ', 'XYZacbxf', '12153131', 'Samsung ', 'Apple smartphone x10']

也可以通过迭代字符串来替换:

to_replace_terms = ['ABCD', 'mobile', 'google']
m = []
for link in links:
    for to_replace_term in to_replace_terms:
        link = link.replace(to_replace_term, '')
    m.append(link)

注意,您需要将替换分配回link,因为可能会发生多个替换。你知道吗

相关问题 更多 >