删除字符串第一个单词的最快/最干净的方法是什么?我知道我可以使用
split
然后迭代数组来获取我的字符串。但我很确定这不是最好的方法。
maxsplit
参数将其限制为仅一次拆分:
>>> s = 'word1 word2 word3'
>>> s.split(' ', 1)
['word1', 'word2 word3']
>>> s.split(' ', 1)[1]
'word2 word3'
一个简单的解决方案是:
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)
更一般地说,如果不知道我们正在谈论哪种自然语言,就不可能回答涉及“单词”的问题。 “杰”有多少个字? “中华人民共和国”怎么样?
如果您的字符串只有一个单词,另一个答案将引发异常,我认为这不是您想要的。
执行此操作的一种方法是使用
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'
str.partition()
就是您要寻找的。
>>> test = "word1 word2 word3"
>>> test.partition(" ")
('word1', ' ', 'word2 word3')
元组中的第三项是您想要的部分。
这么多复杂的答案,解决方案很简单
my_str = "The fox is brown"
res = my_str.split(' ', 1)[1] # res: "fox is brown"