Python 2: AttributeError: 'list' object has no attribute 'strip'
strip()
is a method for strings, you are calling it on a 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 elements to be in a single list (and not a list of lists), you have two options.
- Create an empty list and append elements to it.
- Flatten the list.
To do the first, follow 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']
What you want to do is -
strtemp = ";".join(l)
The first line adds a ;
to the end of MySpace
so that while splitting, it does not give out MySpaceApple
This will join l into one string and then you can just-
l1 = strtemp.split(";")
This works because strtemp is a string which has .split()