Home > Back-end >  Replace the last letter of a word
Replace the last letter of a word

Time:02-14

I want to replace the last letter of a word, especially if the letter is 'T' should be replaced by 'k'.

For example:

input: words = 'GeorgeT wants to playT footballTt'

Output: 'Georgek wants to playk footballTt'

I checked another stackoverflow questions, but I was confused. Please help me!

CodePudding user response:

Split your sentence into words then check the last letter and replace the last letter if necessary. Finally reassemble the words into a sentence.

words = ' '.join([w[:-1]   'k' if w[-1] == 'T' else w for w in words.split()])
print(words)

# Output
'Georgek wants to playk footballTt'

CodePudding user response:

You can use a simple regex here:

import re

words = 'GeorgeT wants to playT footballTt'

output = re.sub(r'T\b', 'k', words)

output: 'GeorgeT wants to playT footballTt'

regex:

T    # match a capital T
\b   # if last letter of a word

CodePudding user response:

First change your sentence into a list of words using the split attribute. Next iterate through the list, changing the last letter of the word if it is a 'T' and create a new list; Last turn the list into a single string using the join() attribute of the string " ".

    list_of_words=words.split()
    new_list_of_words=[]
    for word in list_of_words:
         last_letter = word[-1]
         if last_letter == "T":
            word = word[:-1] 'k'
         new_list_of_words.append(word)
    new_words= " ".join(new_list_of words)
    print(new_words)
      

You can do all of this in one line (replace the loop by a list comprehension ).

  • Related