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

标签 python

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

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

最佳答案

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

关于python - 用空格分隔符打破列表值 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36432373/

相关文章:

python - 将功能应用于 Pandas groupby

Python:NGINX+FLASK 的 uWSGI 配置

python - 消息 'The Twitter REST API v1 is no longer active. Please migrate to API v1.1'

python - 如何使池对键盘中断敏感

python - 使用python中的selenium模块查找html页面中的元素

Python Pandas : float values break down when df. 列 = df.columns.droplevel()

java - Java 世界里有像 CherryPy 或 Cerise 这样的东西吗?

python - 使用 NLP 进行查询 [PYTHON]

Python无法正确读取文件

Python:列出没有索引的网站的所有URL