str.replace()
will replace all occurrences of the string you pass in as the first argument. It doesn't matter here that the first argument here is created from a slice, the str.replace()
method is not given any information as to where that string came from. Instead, the str.replace()
method starts at position 0 and searches forward, it doesn't matter where the substring is found in the input string.
So you are really just doing this:
string_to_replace = s[9:12]
s.replace(string_to_replace, ' ')
or even just
s.replace('111', ' ')
These all have the exact same effect.
Your second example only worked because the s[9:12]
string value is unique in s
; there is only one occurrence to replace, at exactly the right location.
Because s[9:12]
is the string '111'
, you asked Python to replace all occurances of that string in s
with spaces, and there are two such sequences to replace.
You are far better off explicitly slicing the input string:
s = s[:9] + ' ' + s[12:]
That takes all text before the part you want to replace and all the text after, and puts three spaces in between those two substrings.