我有以下字串串列:
list_of_str = ['Notification message', 'Warning message', 'This is the |xxx - show| message.', 'Notification message is defined by |xxx - show|', 'Notification message']
如何獲取最接近尾部并包含的字串show|,并替換show|為Placeholder|?
預期結果:
list_of_str = ['Notification message', 'Warning message', 'This is the |xxx - show| message.', 'Notification message is defined by |xxx - Placeholder|', 'Notification message']
uj5u.com熱心網友回復:
反向迭代,查找替換:
for i, s in enumerate(reversed(list_of_str), 1):
if 'show|' in s:
list_of_str[-i] = s.replace('show|', 'Placeholder|')
break
uj5u.com熱心網友回復:
這應該作業
# reverse the list
for i, x in enumerate(list_of_str[::-1]):
# replace the first instance and break loop
if 'show|' in x:
list_of_str[len(list_of_str)-i-1] = x.replace('show|', 'Placeholder|')
break
list_of_str
['Notification message',
'Warning message',
'This is the |xxx - show| message.',
'Notification message is defined by |xxx - Placeholder|',
'Notification message']
uj5u.com熱心網友回復:
試試這個:
idx = next((idx for idx in reversed(range(len(list_of_str)))
if 'show|' in list_of_str[idx]), 0)
list_of_str[idx] = list_of_str[idx].replace('show|', 'Placeholder|')
您首先找到包含“show|”的最后一個索引 然后你做更換。
另外一個選項:
for idx in reversed(range(len(list_of_str))):
if 'show|' in list_of_str[idx]:
list_of_str[idx] = list_of_str[idx].replace('show|', 'Placeholder|')
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477279.html
