0
word = input("Word: ") 
for n in range(0, len(word)):
 sliced_front = word.replace(word[n:], '')
 sliced_back = word.replace(word[:n+1], '')
 print(sliced_front, sliced_back)

In above code, if I enter 'breatd', this is the output:

     reatd 
    b eatd 
    br atd 
    bre td 
    brea d 
    breat

If I enter 'states', this is the output:

     tate 
    s ates 
    st tes 
    sta es 
    stat s 
    tate 

If I enter 'events', this is the output:

     vnts 
    e ents 
    ev nts 
    eve ts 
    even s 
    event 

Why does python remove 's' twice in the first and last iterations when the input is 'states', while removing 'e' twice only in the first iteration, not in third iteration when input is 'events'?

I want to remove a single character in each iteration. How can I make this stop removing the repeated character twice in a single iteration?

Hanna
  • 11

3 Answers3

1

replace replaces all occurrences of the letter, not by position

You should use a slice instead:

word = 'abcdabc'
for n in range(len(word)):
    print(word[:n]+' '+word[n+1:])

Output:

 bcdabc
a cdabc
ab dabc
abc abc
abcd bc
abcda c
abcdab 
mozway
  • 194,879
  • 13
  • 39
  • 75
0

per python docs: link will replace all instances of that string, if want to only replace first need to specify count parameter

kamster
  • 139
  • 6
0

First of all, replace returns a copy of the string with all occurrences of the old substring replaced by the new one. To replace only the first occurrence of the old substring - you need to use the optional argument count. However, for the need you described, it is probably better to use a slice.

Secondly, there is no need to provide range with a start parameter of 0, as it is the default value of the start parameter.

Putting it all together:

word = input("Word: ") 
for letter in range(len(word)):
    print(word[:letter ] + ' ' + word[letter +1:])

Output (given the input "states"):

tates
s ates
st tes
sta es
stat s
state