Reputation: 1840
I want to split a inner string in order to get every item, the string is into a [()] structure,the object to process could be something like:
[(u'|name1|name2|name3|123|124|065|',)]
or
[(u'|name1|',)]
or
[(u'')]
or even
false
To get the items from the string I only need:
mystring.split('|')
But I think that my final approach is ugly and error-prone:
mylist[0][0].split('|')
How can I get a items list in a clean and pythonic way?
Upvotes: 0
Views: 86
Reputation: 695
I think your approach is correct.
But what about the first and last elements of split('|') result?. They are empty because your strings starts and ends with a '|'.
You could use list comprehension.
[name for name in mylist[0][0].split('|') if name]
Or striping the string before:
mylist[0][0].strip('|').split('|')
Upvotes: 1
Reputation: 3682
I agree that you're getting the best you can, but if you just want a different (equivalent) way of doing it,
from operator import itemgetter
f = itemgetter(0)
f(f(mylist)).split('|')
Upvotes: 1
Reputation: 15165
Just do some previous checking.
If the string can be nested at not constant depth, just wrap the extraction in a loop until it is instance of basestring.
def split(container):
if not container:
return []
return container[0][0].split('|')
Upvotes: 1