1

str.replace() allows to replace a substring in a string with something else.

I have the problem of repeated whitespaces after the replacement:

>>> 'word word to be removed word'.replace('to be removed', '')
'word word  word'

Note the two whitespaces after the second word.

Is there a way to replace a substring with a backspace that would remove one space? (I know that the string will be made of words separated by spaces)

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 4
    Well, in your own words, why do two spaces appear? Can you think of a substring that you could remove from the original text, in order to get the result you want? – Karl Knechtel Feb 23 '21 at 18:00
  • 2
    Alternatively remove [multiple spaces](https://stackoverflow.com/questions/1546226/is-there-a-simple-way-to-remove-multiple-spaces-in-a-string) – RJ Adriaansen Feb 23 '21 at 18:04
  • 1
    Add a space after "`remove`" - ....`.replace('to be removed ', '')`. You can get rid of the problem. –  Feb 23 '21 at 18:06
  • `\w*` also your friend, so *spoiler* instead use `r'\w*to be removed\w*'` – Razzle Shazl Feb 23 '21 at 18:06
  • @KarlKnechtel: well, I cannot - and this is why I asked the question :) `\b` did not work – WoJ Feb 23 '21 at 18:08
  • also consider all the other kind of punctuation that could occur, and group that into `[` `]` e.g. `[ ,.;;']*` or what have you – Razzle Shazl Feb 23 '21 at 18:08
  • How would you expect a backspace to work though? Assuming you know that you want to replace `' '` with it, would it not replace `' '` with a backspace and in the process remove the `'o'` from `'to'` as well since its replacing and not just adding the backspace in? If all you want to do is replace double spaces with single spaces, a simple `str.replace(' ', ' ')` would suffice. – Axe319 Feb 23 '21 at 18:13
  • @RazzleShazl -1: the built-in `.replace` method of strings *in Python* does not use regex at all. – Karl Knechtel Feb 23 '21 at 23:24
  • @KarlKnechtel good to know and probably a good reason to avoid this method unwieldy method :) – Razzle Shazl Feb 23 '21 at 23:31

2 Answers2

2

One solution is to split(), and then join() the result. This also removes pre-and post-whitspaces

>>> ' '.join('word word to be removed word'.replace('to be removed', '').split())
'word word word'
WoJ
  • 27,165
  • 48
  • 180
  • 345
0

You could just add this whitespace at the end of the substring to be removed:

phrase = 'word word to be removed word'

# We add the whitespace at the end
to_remove = 'to be removed ' # instead of 'to be removed'

# Remove a specific substring
phrase = phrase.replace(to_remove, '')

If you have consecutive whitespaces and want to replace them by only one, you can use a regex:

import re

# Replace all consecutive whitespaces by one whitespace
phrase = re.sub(r" +", " ", phrase)
Rivers
  • 1,783
  • 1
  • 8
  • 27