简体   繁体   中英

Python 2.7 : how to extract from between special characters

I have a string like this :

'|||stuff||things|||others||||'

Is there a simple way to extract all the content contained between | characters, so the end result would be something like:

result = ['stuff', 'things', 'others']

edit: I would not know the content of the string in advance, as in i do not know specifically to look for 'stuff', 'things', or 'others', I just know that whatever is between the | characters needs to saved as its own separate string

[i for i in string.split('|') if i!='']

这应该工作

Splitting on one or more | with re.split :

re.split(r'\|+', str_)

This will give empty strings at start and end, to get rid of those use a list comprehension to take only the strings that are truthy :

[i for i in re.split(r'\|+', str_) if i]

Example:

In [193]: str_ = '|||stuff||things|||others||||'

In [194]: re.split(r'\|+', str_)
Out[194]: ['', 'stuff', 'things', 'others', '']

In [195]: [i for i in re.split(r'\|+', str_) if i]
Out[195]: ['stuff', 'things', 'others']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM