删除Python字符串中的第一个单词?

问题描述 投票:0回答:5

删除字符串第一个单词的最快/最干净的方法是什么?我知道我可以使用

split
然后迭代数组来获取我的字符串。但我很确定这不是最好的方法。

python string
5个回答
112
投票

我认为最好的方法是拆分,但通过提供

maxsplit
参数将其限制为仅一次拆分:

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

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)

更一般地说,如果不知道我们正在谈论哪种自然语言,就不可能回答涉及“单词”的问题。 “杰”有多少个字? “中华人民共和国”怎么样?


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')

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


0
投票

这么多复杂的答案,解决方案很简单

my_str = "The fox is brown"
res = my_str.split(' ', 1)[1] # res: "fox is brown"
© www.soinside.com 2019 - 2024. All rights reserved.