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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12883376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:06:03  来源:igfitidea点击:

Remove the first word in a Python string?

pythonstring

提问by Matthieu Riegler

What's the quickest/cleanest way to remove the first word of a string? I know I can use splitand then iterate on the array to get my string. But I'm pretty sure it's not the nicest way to do it.

删除字符串第一个单词的最快/最干净的方法是什么?我知道我可以使用split然后迭代数组来获取我的字符串。但我很确定这不是最好的方法。

Ps: I'm quite new to python and I don't know every trick.

Ps:我对python很陌生,我不知道每一个技巧。

Thanks in advance for your help.

在此先感谢您的帮助。

采纳答案by ovgolovin

I think the best way is to split, but limit it to only one split by providing maxsplitparameter:

我认为最好的方法是拆分,但通过提供maxsplit参数将其限制为只有一个拆分:

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

回答by Gareth Latty

Presuming you can guarantee the words are separated by a single space, str.partition()is what you are looking for.

假设您可以保证单词由一个空格分隔,这str.partition()就是您要查找的内容。

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

The third item in the tuple is the part you want.

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

回答by Julian

The other answer will raise an exception if your string only has one word, which I presume is not what you want.

如果您的字符串只有一个单词,则另一个答案将引发异常,我认为这不是您想要的。

One way to do this instead is to use the str.partitionfunction.

执行此操作的一种方法是使用该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'

回答by georg

A naive solution would be:

一个天真的解决方案是:

text = "funny cheese shop"
print text.partition(' ')[2] # cheese shop

However, that won't work in the following (admittedly contrived) example:

但是,这在以下(公认的人为)示例中不起作用:

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

To handle this, you're going to need regular expressions:

为了解决这个问题,您将需要正则表达式:

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

More generally, it's impossible to answer a question involving "word" without knowing which natural language we're talking about. How many words is "J'ai"? How about "中华人民共和国"?

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