python按指定次数分割
发布于 2021-01-29 15:04:59
在以下字符串中,我如何以以下方式拆分字符串
str1="hi\thello\thow\tare\tyou"
str1.split("\t")
n=1
Output=["hi"]
n=2
output:["hi","hello"]
关注者
0
被浏览
50
1 个回答
-
str1.split('\t', n)[:-1]
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']