Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a python list by comma

Tags:

python

list

I have a list similar to:

industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"]

How can I split this list so that the output would be something like:

industries_list = [["Computers","Internet"],["Photography","Tourism"],["Motoring","Manufacturing"]]

I have tried converting it to string, split it by comma and then put it back into a list, but that didn't give my the results I was looking for.

like image 998
Renier Avatar asked Mar 10 '26 14:03

Renier


1 Answers

Using List Comprehension:

>>> industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"]
>>> [s.split(',') for s in industries_list]
[['Computers', ' Internet'], ['Photography', ' Tourism'], ['Motoring', ' Manufacturing']]

And to remove the white-space:

>>> from string import strip
>>> [map(strip, s.split(',')) for s in industries_list]
[['Computers', 'Internet'], ['Photography', 'Tourism'], ['Motoring', 'Manufacturing']]

You could also use pure list-comprehension (embedded list comprehension):

>>> [[w.strip() for w in s.split(',')] for s in industries_list]
[['Computers', 'Internet'], ['Photography', 'Tourism'], ['Motoring', 'Manufacturing']]
like image 113
Inbar Rose Avatar answered Mar 12 '26 02:03

Inbar Rose