Python 如何用退格替换字符串?

Python 如何用退格替换字符串?,python,python-3.x,string,replace,str-replace,Python,Python 3.x,String,Replace,Str Replace,允许用其他内容替换字符串中的子字符串 我遇到了替换后重复出现空白的问题: >>> 'word word to be removed word'.replace('to be removed', '') 'word word word' 注意第二个单词后面的两个空格 有没有一种方法可以用一个退格来替换一个子字符串,从而删除一个空格?(我知道字符串将由空格分隔的单词组成)您只需在要删除的子字符串末尾添加此空格即可: phrase = 'word word to be remov

允许用其他内容替换字符串中的子字符串

我遇到了替换后重复出现空白的问题:

>>> 'word word to be removed word'.replace('to be removed', '')
'word word  word'
注意第二个
单词
后面的两个空格


有没有一种方法可以用一个退格来替换一个子字符串,从而删除一个空格?(我知道字符串将由空格分隔的单词组成)

您只需在要删除的子字符串末尾添加此空格即可:

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, '')
如果您有连续的空格,并且只想用一个空格替换它们,则可以使用正则表达式:

import re

# Replace all consecutive whitespaces by one whitespace
phrase = re.sub(r" +", " ", phrase)

一种解决方案是
split()
,然后
join()
结果。这也会删除前空格和后空格

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

用你自己的话说,为什么会出现两个空格?你能想出一个可以从原始文本中删除的子字符串,以获得你想要的结果吗?或者删除在“
删除”-..
之后添加一个空格。替换('to remove','')
。你可以解决这个问题。
\w*
也是你的朋友,所以改用
r'\w*来删除\w*
@KarlKnechtel:我不能-这就是为什么我问这个问题:)
\b
不起作用