如何在 Python 字符串中删除第一个单词?

50

如何最快、最简单地删除字符串的第一个单词?我知道可以使用 split 并迭代数组来获取字符串。但我相信这不是最好的方法。

4个回答

111

我认为最好的方法是分割字符串,但通过提供 maxsplit 参数将其限制为仅进行一次分割:

>>> s = 'word1 word2 word3'
>>> s.split(' ', 1)
['word1', 'word2 word3']
>>> s.split(' ', 1)[1]
'word2 word3'

6
他想从字符串中移除第一个单词,因此命令应为 a = a.split(' ', 1)[1] - Ionut Hulub
这个怎样修改才能做到边界安全? - gandolf
比我尝试的这个要干净得多:' '.join(s.split()[1:]) - Kelsius

23
一个天真的解决方案可能是:
text = "funny cheese shop"
print text.partition(' ')[2] # cheese shop

然而,在下面这个例子(虽然很牵强)中,它不起作用:

text = "Hi,nice people"
print text.partition(' ')[2] # people

为了处理这个问题,您需要使用正则表达式:

import re
print re.sub(r'^\W*\w+\W*', '', text)

一般来说,如果不知道具体是哪种自然语言,就很难回答一个涉及到“单词”的问题。比如,“J'ai”有多少个单词?“中华人民共和国”又有多少个?


3

另一个答案会在你的字符串只有一个单词时引发异常,我想这不是你想要的。

相反,一种方法是使用 str.partition 函数。

>>> s = "foo bar baz"
>>> first, _, rest = s.partition(" ")
>>> rest or first
'bar baz'

>>> s = "foo"
>>> first, _, rest = s.partition(" ")
>>> rest or first
'foo'

1

假设您可以保证单词之间只有一个空格,那么str.partition()就是您要找的。

>>> test = "word1 word2 word3"
>>> test.partition(" ")
('word1', ' ', 'word2 word3')

元组中的第三项是您想要的部分。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接