python按指定的次数拆分
在以下字符串中,如何按以下方式拆分字符串python按指定的次数拆分,python,Python,在以下字符串中,如何按以下方式拆分字符串 str1="hi\thello\thow\tare\tyou" str1.split("\t") n=1 Output=["hi"] n=2 output:["hi","hello"] 有一个可选的第二个参数,即拆分的次数。我们用切片删除列表中的最后一项(剩余项) 例如: a = 'foo,bar,baz,hello,world' print(a.split(',', 2)) # ['foo', 'bar', 'baz,hello,world']
str1="hi\thello\thow\tare\tyou"
str1.split("\t")
n=1
Output=["hi"]
n=2
output:["hi","hello"]
有一个可选的第二个参数,即拆分的次数。我们用切片删除列表中的最后一项(剩余项)
例如:
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']
为什么不应该-n@Rajeev
[:-1]
删除列表的最后一个元素。它与[:len(lst)]
相同<代码>[:-len(lst)]删除整个列表。在你的例子中,n
是列表的长度。但是如果之后剩下两到三个呢splitting@Rajeev您已经提供了所需的拆分次数-Python只会拆分n次
,您需要做的就是去除剩余部分是的,这正是我想要的。如何去除剩余部分[:-1]无法确定是否执行此操作,因为它仅删除最后一个元素
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']