在List - Python中查找并替换字符串

时间:2018-05-17 16:23:07

标签: python

我有一个清单

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

我想将字符串Base替换为Fine,即精细核心,我尝试了下面的代码,但它的工作

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

print(nums1)

我该如何开展这项工作

2 个答案:

答案 0 :(得分:3)

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

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"

答案 1 :(得分:0)

我认为您不需要将re拖入此中。如果我们使用OP的替换逻辑和@ Ajax1234的循环结构,我们得到:

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

<强> RESULT

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