-1

I am making a "Wordle" type of game in Python and wanted to remove the last letters you wrote when you press backspace and it worked in most cases but I have a problem if your word has the letter that are the same for example "start".

I tried using the .replace() function like this:

word = 'start'
new_word = word.replace(word[4], '', 1)
print(new_word)

But the result isn't 'star', but rather 'sart'. As you see it replaces the first 't' and not the last. Does anyone know how to replace the last 't' but the solution needs to work on any case, like in 'aaaaa' it just needs to replace the last 'a'?

macropod
  • 12,757
  • 2
  • 9
  • 21
Code Freak
  • 13
  • 6

2 Answers2

-2

Extract from the total length of the word the last character, like this for example:

word = 'start'

new_word = word[:len(word)-1]

print(new_word)

Fernando
  • 29
  • 5
-2
word = 'start'
new_word = word.replace(word[1], word[4]) #replaces letter 1 with letter 4
new_word = new_word[:-1] #removes last letter
print(new_word)
fbn001
  • 31
  • 7
  • 1
    There is no need for this line of code `new_word = word.replace(word[1], word[4])` he just need to slice the string. – Oghli Nov 19 '22 at 10:26