Python在字符串中获取x个第一个单词

Gui*_*ume 15 python string

我正在寻找一个代码,它在脚本中包含4(或5)个第一个单词.我试过这个:

import re    
my_string = "the cat and this dog are in the garden"    
a = my_string.split(' ', 1)[0]
b = my_string.split(' ', 1)[1]
Run Code Online (Sandbox Code Playgroud)

但我不能超过2个字符串:

a = the
b = cat and this dog are in the garden
Run Code Online (Sandbox Code Playgroud)

我想拥有:

a = the
b = cat
c = and
d = this
...
Run Code Online (Sandbox Code Playgroud)

bos*_*jak 22

split()方法的第二个参数是限制.不要使用它,你会得到所有的话.像这样使用它:

my_string = "the cat and this dog are in the garden"    
splitted = my_string.split()

first = splitted[0]
second = splitted[1]

...
Run Code Online (Sandbox Code Playgroud)

此外,split()每次想要一个单词时都不要打电话,这很贵.做一次,然后稍后使用结果,就像在我的例子中一样.
如您所见,不需要添加' '分隔符,因为split()function(None)的默认分隔符匹配所有空格.但是,如果您不想拆分,则可以使用它Tab.

  • @Naman可以肯定,`split`和`rsplit`都有第二个参数,即maxsplit`。因此,要获取第一个单词,请使用`sentence.split('',1)`,要获取最后一个单词,请使用`sentence.rsplit('',1)`。这应该是您所需要的。 (2认同)

Two*_*ist 17

您可以在split创建的列表上使用切片表示法:

my_string.split()[:4] # first 4 words
my_string.split()[:5] # first 5 words
Run Code Online (Sandbox Code Playgroud)

注意这些是示例命令.您应该使用其中一个,而不是两个都使用.

  • 这不会多次调用 `split`。它调用一次并创建它返回的列表的“切片副本”。这就是为什么 `l2 = l1[:]` 是在 Python 中制作列表副本的有效方法。它不会创建 `n` 个子列表。 (2认同)

koj*_*iro 7

您可以很容易地在空格上拆分字符串,但如果您的字符串中没有足够的单词,则在列表为空的情况下,分配将失败.

a, b, c, d, e = my_string.split()[:5] # May fail
Run Code Online (Sandbox Code Playgroud)

最好保持列表不变,而不是将每个成员分配给一个单独的名称.

words = my_string.split()
at_most_five_words = words[:5] # terrible variable name
Run Code Online (Sandbox Code Playgroud)

这是一个可怕的变量名称,但我用它来说明你不能保证得到五个单词这一事实 - 你只能保证得到最多五个单词.