Python 2: AttributeError: list object has no attribute strip

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.

  1. Create an empty list and append elements to it.
  2. 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()

Python 2: AttributeError: list object has no attribute strip

This should be what you want:

[x for y in l for x in y.split(;)]

output:

[Facebook, Google+, MySpace, Apple, Android]

Leave a Reply

Your email address will not be published. Required fields are marked *