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"
我认为你不需要把
re
扯进去。如果我们将OP的替换逻辑与@Ajax1234的循环结构结合使用,我们会得到:结果
您可以在列表理解中使用
re.sub
。这样,在nums
中的任何元素中处理'Base Core'
的多次出现会更简单:输出:
regex
说明:相关问题 更多 >
编程相关推荐