Convert string to tuple

I have a line like this:

'| Action and Adventure | Drama | Science fiction | Fantasy |

How can I convert it to a tuple or list?

Thank.

+3
source share
6 answers
>>> 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 prefer a tuple, then:

>>> tuple(item for item in s.split('|') if item.strip())
('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')
>>> 
+8
source

Do you want str.split():

>>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
>>> s.split('|')
['', 'Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy', '']
+1
source

|, :

myStr.split('|')

(, , ), :

def myFilter(el): return len(el) > 0
filter(myFilter, myStr.split('|'))
+1

Strip 'String'.strip(' | ')

   >>> heading = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
   >>> tuple(heading.strip('|').split('|'))
   ('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')

'' [1: -1]

   >>> heading = '|Action and Adventure|Drama|Science-Fiction|Fantasy|'
   >>> tuple(heading[1:-1].split('|'))
   ('Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy')

tuple().

+1

strip() , split() divvies :

>>> s.strip('|').split('|')
['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy']
+1

List

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

seq = tuple(seq)

If you want to remove empty elements, skip the output through filter(None, seq). If you |always accept external , just draw seq[1:-1].

0
source

Source: https://habr.com/ru/post/1769271/


All Articles