Reputation: 723
I have a string that I'm trying to replace when it has spaces surrounding the character like below:
>>> strvar = " a a b b "
>>> strvar.replace('a', 'r')
" r r b b " # WORKS!
>>> strvar.replace('a ', 'r ')
" r r b b " # WORKS!
>>> strvar.replace(' a', ' r')
" r r b b " # WORKS!
>>> strvar.replace(' a ', ' r ')
" r a b b " # only first occurrence is replaced
>>> strvar.replace(' b ', ' r ')
" a a r b " # only first occurrence is replaced
my question is that why can't python replace work on the last two situations??
Upvotes: 0
Views: 1285
Reputation: 174624
Your problem is that you only have one instance of the string to be replaced. Lets break down your string:
" a a b b "
This is:
a
a
b
b
When you ask to replace ' a '
it is looking for:
a
There is only one set of this (starting from left), hence only one substitution.
Upvotes: 1
Reputation: 11041
Use a regex instead, as it will prevent issues caused by overlapping. See the following regex:
r'(?<= )a(?= )'
Replace with:
r
(?<= )
is a positive lookbehind group that asserts the match is following " ".(?= )
is a positive lookahead group that asserts the match is followed by " ".Upvotes: 4
Reputation: 1019
it is not working because the sub-strings found are overlapping. first occurrence found is ' a ', the rest of the string is 'a b b ', so of course it will not match ' a ' again
Upvotes: 0
Reputation: 2624
The issue is that there is an overlap in the occurrences.
In the string: " a a b b "
There are no two occurrences of " a "
because the spaces overlap. After the first occurrence is replaced the rest of the string is "a b b"
which does not match your pattern
Upvotes: 0