strip() is a method for strings, you call it on list , hence the error.
>>> 'strip' in dir(str) True >>> 'strip' in dir(list) False
To do what you want, just do
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android'] >>> l1 = [elem.strip().split(';') for elem in l] >>> print l1 [['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
Since you want the items to be on the same list (rather than a list of lists), you have two options.
- Create an empty list and add items to it.
- Smooth the list.
To do the first, execute the code:
>>> l1 = [] >>> for elem in l: l1.extend(elem.strip().split(';')) >>> l1 ['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
To do the second, use itertools.chain
>>> l1 = [elem.strip().split(';') for elem in l] >>> print l1 [['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']] >>> from itertools import chain >>> list(chain(*l1)) ['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
Sukrit kalra
source share