0

如果我有一个字符串,例如'the quick brown fox',如何从原始字符串中删除连续的单词,例如“quick brown”以获取'the fox'?我试过strip()了,但没有用,我不太确定还能做什么。

4

3 回答 3

3

使用str.replace()

In [2]: strs='the quick brown fox'

In [3]: strs.replace('quick brown','')
Out[3]: 'the  fox'

In [4]: " ".join(strs.replace('quick brown','').split())
Out[4]: 'the fox'                          #single space between 'the' and 'fox'

help()str.replace()

S.replace(old, new[, count]) -> str

Return a copy of S with all occurrences of substring
old replaced by new.  If the optional argument count is
given, only the first count occurrences are replaced.
于 2012-12-27T22:01:23.207 回答
1

不能原始字符串中删除单词。字符串是不可变的;见这里

“字符串和元组是不可变的序列类型:此类对象一旦创建就无法修改。”

使用replace返回字符串的副本

于 2012-12-27T22:04:44.920 回答
-1
mystring.replace(" quick brown ", " ", 1)
于 2012-12-27T22:04:20.710 回答