Arash77
Arash77

Reputation: 723

python string replace() method when replacing a character with surrounding spaces only replaces the first occurrence

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

Answers (4)

Burhan Khalid
Burhan Khalid

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:

  1. Space
  2. a
  3. Space
  4. a
  5. Space
  6. b
  7. Space
  8. b
  9. Space

When you ask to replace ' a ' it is looking for:

  1. Space
  2. a
  3. Space

There is only one set of this (starting from left), hence only one substitution.

Upvotes: 1

Unihedron
Unihedron

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

avim
avim

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

odedsh
odedsh

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

Related Questions