删除字符串第一个单词的最快/最干净的方法是什么?我知道我可以使用split然后迭代数组来获取我的字符串.但我很确定这不是最好的方法.
Ps:我对python很新,我不知道每个技巧.
在此先感谢您的帮助.
ovg*_*vin 73
我认为最好的方法是拆分,但通过提供maxsplit参数将其限制为只有一个拆分:
>>> s = 'word1 word2 word3'
>>> s.split(' ', 1)
['word1', 'word2 word3']
>>> s.split(' ', 1)[1]
'word2 word3'
Run Code Online (Sandbox Code Playgroud)
geo*_*org 18
一个天真的解决方案是:
text = "funny cheese shop"
print text.partition(' ')[2] # cheese shop
Run Code Online (Sandbox Code Playgroud)
但是,这不适用于以下(公认的人为)示例:
text = "Hi,nice people"
print text.partition(' ')[2] # people
Run Code Online (Sandbox Code Playgroud)
要处理这个问题,你需要正则表达式:
import re
print re.sub(r'^\W*\w+\W*', '', text)
Run Code Online (Sandbox Code Playgroud)
更一般地说,如果不知道我们正在谈论的是哪种自然语言,就不可能回答涉及"单词"的问题."J'ai"有多少字?"中华人民共和国"怎么样?