python - 查找并替换列表中的字符串 - Python

标签 python

我有一个 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/

相关文章:

python - 如何将文本拆分为句子?

python名称修饰和全局变量

python - 用 pytorch 计算预测函数的损失

python - 使 python raw_input() 或 input() 不等待

"flags"概念的 Pythonic 方式

python - Django 表单前缀与表单集

python - 如何适应文档?

python - Pymongo 如何设置 read_preference

python - 如何解决 'Error while installing steem-python'

python - 关于 asyncio 的说明