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.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With