Reputation: 901
I have a list of strings and some text strings as follows:
my_list = ['en','di','fi','ope']
test_strings = ['you cannot enter', 'the wound is open', 'the house is clean']
I would like to replace the last words in the test_strings with their corresponding strings from the list above, if they appear in the list. i have written a for loop to capture the pattern, but do not know how to proceed with the replacement (?).
for entry in [entry for entry in test_strings]:
if entry.split(' ', 1)[-1].startswith(tuple(my_list)):
output = entry.replace(entry,?)
as output I would like to have:
output = ['you cannot en', 'the wound is ope', 'the house is clean']
Upvotes: 0
Views: 507
Reputation: 135
my_list = ['en', 'di', 'fi', 'ope']
test_strings = ['you cannot enter', 'the wound is open', 'the house is clean']
for i in range(len(test_strings)):
temp = test_strings[i].split(" ")
last_word = temp[-1]
for j in my_list:
if last_word.startswith(j):
break
else:
j = last_word
temp[-1] = j
test_strings[i] = " ".join(temp)
After this, test_strings
will be what is required.
For replacing the text, the index
of the list has been reassigned to the new text.
Upvotes: 1
Reputation: 655
for i,v in enumerate(test_strings):
last_term = v.split(' ')[-1]
for k in my_list:
if last_term.startswith(k):
test_strings[i] = v.replace(last_term,k)
break
print(test_strings)
['you cannot en', 'the wound is ope', 'the house is clean']
Upvotes: 1