从字符串中删除单词

时间:2012-12-27 22:00:08

标签: python string

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

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

无法原始字符串中删除字词。字符串是不可改变的;见here

  

“字符串和元组是不可变的序列类型:创建后不能修改此类对象。”

使用replace会返回字符串的副本

答案 2 :(得分:-1)

mystring.replace(" quick brown ", " ", 1)