简体   繁体   English

Python 2.7:如何从特殊字符之间提取

[英]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

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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