Reputation: 189
I have a string like this:
'|Action and Adventure|Drama|Science-Fiction|Fantasy|'
How can I convert it to a tuple or a list?
Thanks.
Upvotes: 3
Views: 10756
Reputation: 118490
seq = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'.split('|')
seq = tuple(seq)
If you want to strip empty items, pass the output through filter(None, seq)
. If you assume outer |
always, just slice with seq[1:-1]
.
Upvotes: 0
Reputation: 177600
strip()
gets rid of the leading and trailing chars, split()
divvies up the remainder:
>>> s.strip('|').split('|')
['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']
Upvotes: 1
Reputation: 26098
Strip 'string'.strip('|')
>>> heading = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> tuple(heading.strip('|').split('|'))
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
Slice 'string'[1:-1]
>>> heading = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> tuple(heading[1:-1].split('|'))
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
For List remove the tuple() call.
Upvotes: 1
Reputation: 74705
>>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>>
>>> [item for item in s.split('|') if item.strip()]
['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']
>>>
If you'd rather have a tuple then:
>>> tuple(item for item in s.split('|') if item.strip())
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
>>>
Upvotes: 8
Reputation: 44346
If you want to just split your string at the |
character you use:
myStr.split('|')
If you also want all zero-length element removed (like the ones from the ends) you:
def myFilter(el): return len(el) > 0
filter(myFilter, myStr.split('|'))
Upvotes: 1
Reputation: 33716
You want str.split()
:
>>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> s.split('|')
['', 'Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy', '']
Upvotes: 1