删除字符串的第一个单词的最快/最干净的方法是什么?我知道我可以使用split
,然后迭代数组来获取我的字符串。但我很确定这不是最好的方法。删除Python字符串中的第一个单词?
ps:我对Python很新,我不知道每一个窍门。
在此先感谢您的帮助。
删除字符串的第一个单词的最快/最干净的方法是什么?我知道我可以使用split
,然后迭代数组来获取我的字符串。但我很确定这不是最好的方法。删除Python字符串中的第一个单词?
ps:我对Python很新,我不知道每一个窍门。
在此先感谢您的帮助。
假设你能保证用一个空格隔开的话,str.partition()
是你是什么寻找。
>>> test = "word1 word2 word3"
>>> test.partition(" ")
('word1', ' ', 'word2 word3')
元组中的第三项是你想要的部分。
如果你的字符串只有一个单词,我认为不是你想要的,另一个答案会引发异常。
改为此的一种方法是使用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'
一个天真的解决办法是:
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”有多少个单词? “中华人民共和国”怎么样?
split,pop,join? – Prasanth