I have a small problem with list. So i have a list called l
:
l = ['Facebook;Google+;MySpace', 'Apple;Android']
And as you can see I have only 2 strings in my list. I want to separate my list l
by ';' and put my new 5 strings into a new list called l1
.
How can I do that?
And also I have tried to do this like this:
l1 = l.strip().split(';')
But Python give me an error:
AttributeError: 'list' object has no attribute 'strip'
So if 'list' object has no attribute 'strip' or 'split', how can I split a list?
Thanks
If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
The remove() method is one of the ways you can remove elements from a list in Python. The remove() method removes an item from a list by its value and not by its index number.
It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.
The Python String strip() function works only on strings and will return an error if used on any other data type like list, tuple, etc.
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.
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()
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