Antonio Pardo
Antonio Pardo

Reputation: 189

Convert string to a tuple

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

Answers (6)

Matt Joiner
Matt Joiner

Reputation: 118490

List

seq = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'.split('|')

Tuple

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

Mark Tolonen
Mark Tolonen

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

kevpie
kevpie

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

Manoj Govindan
Manoj Govindan

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

Alin P.
Alin P.

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

jathanism
jathanism

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

Related Questions