Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python按指定的次数拆分_Python - Fatal编程技术网

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']