python按指定的次数分割

Raj*_*eev 3 python

在以下字符串中,我如何以下列方式拆分字符串

str1="hi\thello\thow\tare\tyou"
str1.split("\t")
n=1
Output=["hi"]

 n=2 
output:["hi","hello"]
Run Code Online (Sandbox Code Playgroud)

Vol*_*ity 11

str1.split('\t', n)[:-1]
Run Code Online (Sandbox Code Playgroud)

str.split有一个可选的第二个参数,即拆分的次数.我们用切片删除列表中的最后一项(剩余部分).

例如:

a = 'foo,bar,baz,hello,world'
print(a.split(',', 2))
# ['foo', 'bar', 'baz,hello,world']  #only splits string twice
print(a.split(',', 2)[:-1])  #removes last element (leftover)
# ['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)