使用空格分隔符打破列表值 - Python

时间:2016-04-05 16:45:25

标签: python

我试图将每个列表值分解为如下所示的两个变量,其中以space作为分隔符。但是我无法在列表中这样做。有没有更好的方法呢?请告诉我。

 List1 = ['help  show this help message and exit','file  Output to the text file']

 for i in range(strlist.__len__()):
      # In this loop I want to break each list into two variables i.e. help, show this help message and exit in two separate string variables. 
      print(strlist[i])

1 个答案:

答案 0 :(得分:5)

使用split(None, 1)分隔第一个空格:

>>> for item in List1:
...     print(item.split(None, 1))
... 
['help', 'show this help message and exit']
['file', 'Output to the text file']

如果需要,您可以将结果解包到单独的变量中:

>>> for item in List1:
...     key, value = item.split(None, 1)
...     print(key)
...     print(value)
... 
help
show this help message and exit
file
Output to the text file