[英]Find and replace a string in List - Python
我有一個清單
nums = ['Aero', 'Base Core Newton', 'Node']
我想將字符串Base替換為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)
我該如何工作
您可以在列表re.sub
中使用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"
我不認為你需要拖動re
進入這個。 如果我們將OP的替換邏輯與@ Ajax1234的循環結構一起使用,則會得到:
nums = ['Aero', 'Base Core Newton', 'Node']
new_nums = [i.replace('Base','Fine') for i in nums]
結果
['Aero', 'Fine Core Newton', 'Node']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.