我有一个 list
nums = ['Aero', 'Base Core Newton', 'Node']
我想用 Fine 替换字符串 Base ,即 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)
我怎样才能完成这项工作
最佳答案
您可以在列表理解中使用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']
正则表达式
解释:
^ -> 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"
关于python - 查找并替换列表中的字符串 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50396271/