在列表Python中查找并替换字符串

2024-05-19 01:34:30 发布

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

我有一张单子

nums = ['Aero', 'Base Core Newton', 'Node']

我想用Fine(即Fine Core)替换字符串基,我尝试了下面的代码,但没有效果

nums = ['Aero', 'Base Core Newton', 'Node']
nums1=[]
for i in nums:
    if 'Base' in i:
        i.replace('Base','Fine')
        nums1.append(i)

print(nums1)

我该怎么做


Tags: 字符串代码incorenodeforbaseif
2条回答

我认为你不需要把re扯进去。如果我们将OP的替换逻辑与@Ajax1234的循环结构结合使用,我们会得到:

nums = ['Aero', 'Base Core Newton', 'Node']
new_nums = [i.replace('Base','Fine') for i in nums]

结果

['Aero', 'Fine Core Newton', 'Node']

您可以在列表理解中使用re.sub。这样,在nums中的任何元素中处理'Base Core'的多次出现会更简单:

import re
nums = ['Aero', 'Base Core Newton', 'Node']
new_nums = [re.sub('^Base(?=\sCore)', 'Fine', i) for i in nums]

输出:

['Aero', 'Fine Core Newton', 'Node']

regex说明:

^ -> start of line anchor, anything proceeding must be at the start of the string
Base -> matches the "Base" in the string
?= -> positive lookahead, ^Base will not be matched unless the following pattern in parenthesis is found after ^Base
\sCore -> matches a single space, and then an occurrence of "Core"

相关问题 更多 >

    热门问题