close

[Solved] Python 2: AttributeError: ‘list’ object has no attribute ‘strip’

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python 2: AttributeError: ‘list’ object has no attribute ‘strip’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python 2: AttributeError: ‘list’ object has no attribute ‘strip’ Error Occurs?

Today I get the following error Python 2: AttributeError: ‘list’ object has no attribute ‘strip’ in python.

How To Solve Python 2: AttributeError: ‘list’ object has no attribute ‘strip’ Error ?

  1. How To Solve Python 2: AttributeError: 'list' object has no attribute 'strip' Error ?

    To Solve Python 2: AttributeError: 'list' object has no attribute 'strip' Error 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-

  2. Python 2: AttributeError: 'list' object has no attribute 'strip'

    To Solve Python 2: AttributeError: 'list' object has no attribute 'strip' Error 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-

Solution 1


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']

Solution 2

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()

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read