我正在寻找一个在脚本中使用第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]
但是我不能接受超过2个字符串:
a = the
b = cat and this dog are in the garden
我想拥有:
a = the
b = cat
c = and
d = this
...
该split()
方法的第二个参数是限制。不要使用它,您会得到所有的话。像这样使用它:
my_string = "the cat and this dog are in the garden"
splitted = my_string.split()
first = splitted[0]
second = splitted[1]
...
另外,不要split()
每次都想打电话时打电话,这很昂贵。只需执行一次,然后再使用结果,例如在我的示例中。
如您所见,' '
由于split()
函数(None
)的默认定界符与所有空格匹配,因此无需添加定界符。但是,如果您不想分裂,可以使用它Tab
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句