Skip to content
Advertisement

How to replace only the last character in a string but not earlier occurrences of the same character?

I want to find which word’s last character is ‘e’ and I would like to replace ‘e’ with ‘ing’. After this process want to append these in the array such as new words

words= ['example', 'serve', 'recognize', 'ale']


for x in words:
    size = len(x)
    if "e" == x[size - 1]:
       words.append(x.replace(x[-1], 'ing'))

print(words)

output

['example', 'serve', 'recognize', 'ale', 'ingxampling', 'singrving', 'ringcognizing', 'aling']

I want to get the output like this

['example', 'serve', 'recognize', 'ale', 'exampling', 'serving', 'recognizing', 'aling']

Advertisement

Answer

Try this:

words = ['example', 'serve', 'recognize', 'ale']

for x in words:
    if x[-1] == 'e':
       words.append(x[:-1] + 'ing')

print(words)

Or if you want a 1 liner:

words = [*words, *[x[:-1] + 'ing' for x in words if x[-1] == 'e']]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement