Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking List value with space delimiter - Python

Tags:

python

I am trying to break each list value as shown below into two variables with space as its delimiter. But i am not able to do so in Lists. Is there any better way to do it? Kindly let me know.

 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])
like image 383
Goutam Avatar asked May 15 '26 23:05

Goutam


1 Answers

Split by first space(s) with 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']

You can then unpack the result into separate variables, if needed:

>>> 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
like image 145
alecxe Avatar answered May 18 '26 13:05

alecxe