Python 2.7:如何从特殊字符之间提取
我有这样一个字符串:Python 2.7:如何从特殊字符之间提取,python,string,extract,Python,String,Extract,我有这样一个字符串: '|||stuff||things|||others||||' 是否有一种简单的方法可以提取|个字符之间包含的所有内容,因此最终结果如下: result = ['stuff', 'things', 'others'] 编辑:我不会事先知道字符串的内容,因为在我不知道如何专门查找“stuff”、“things”或“others”时,我只知道字符之间的任何内容都需要保存为自己单独的字符串,在一个或多个上使用re.split: re.split(r'\|+', str_)
'|||stuff||things|||others||||'
是否有一种简单的方法可以提取|个字符之间包含的所有内容,因此最终结果如下:
result = ['stuff', 'things', 'others']
编辑:我不会事先知道字符串的内容,因为在我不知道如何专门查找“stuff”、“things”或“others”时,我只知道字符之间的任何内容都需要保存为自己单独的字符串,在一个或多个
上使用re.split
:
re.split(r'\|+', str_)
这将在开始和结束时提供空字符串,以消除那些使用列表理解仅获取真实字符串的字符串:
示例:
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']
在一个或多个
|
上使用re.split进行拆分
:
re.split(r'\|+', str_)
这将在开始和结束时提供空字符串,以消除那些使用列表理解仅获取真实字符串的字符串:
示例:
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']
这应该行得通
这应该行得通