I have the following list of strings:
list_of_str = ['Notification message', 'Warning message', 'This is the |xxx - show| message.', 'Notification message is defined by |xxx - show|', 'Notification message']
How can I get the string that is closest to the tail and contains show|
, and substitute show|
by Placeholder|
?
The expected result:
list_of_str = ['Notification message', 'Warning message', 'This is the |xxx - show| message.', 'Notification message is defined by |xxx - Placeholder|', 'Notification message']
CodePudding user response:
Reverse iteration, find and replace:
for i, s in enumerate(reversed(list_of_str), 1):
if 'show|' in s:
list_of_str[-i] = s.replace('show|', 'Placeholder|')
break
CodePudding user response:
This should work
# 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']
CodePudding user response:
Try this:
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|')
You first find the last index containing "show|" and then you do the replacement.
Another option:
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