如何替换字符串列表中字符串的具体子字符串?
How to substitute the concrete substring of a string in the string's list?
我有以下字符串列表:
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']
试试这个:
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
反向迭代,查找并替换:
for i, s in enumerate(reversed(list_of_str), 1):
if 'show|' in s:
list_of_str[-i] = s.replace('show|', 'Placeholder|')
break
这应该有效
# 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']
我有以下字符串列表:
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']
试试这个:
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
反向迭代,查找并替换:
for i, s in enumerate(reversed(list_of_str), 1):
if 'show|' in s:
list_of_str[-i] = s.replace('show|', 'Placeholder|')
break
这应该有效
# 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']