从字符串中删除单词

2024-06-02 05:51:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个字符串,比如'the quick brown fox',那么如何从原始字符串中删除连续的单词,比如“quick brown”来获得'the fox'?我尝试了strip(),但没有成功,我不太确定还能做什么。在


Tags: the字符串quick单词stripfoxbrown
3条回答
mystring.replace(" quick brown ", " ", 1)

您无法从原始字符串中删除单词。字符串是不可变的;请参见here

"Strings and tuples are immutable sequence types: such objects cannot be modified once created."

使用^{}返回字符串的副本。在

使用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()

^{pr2}$

相关问题 更多 >