Reputation: 29987
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)
Upvotes: 1
Views: 1242
Reputation: 29987
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'
Upvotes: 2
Reputation: 1923
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)
Upvotes: 1