11
我使用正则表达式使用多个分隔符分割字符串。但是如果我的两个分隔符在字符串中彼此相邻,它会在结果列表中放入一个空字符串。例如:在Python中使用多个分隔符分割字符串
re.split(',|;', "This,is;a,;string")
结果
['This', 'is', 'a', '', 'string']
有什么办法,以避免让我的列表中''
不添加,;
作为分隔符?
我使用正则表达式使用多个分隔符分割字符串。但是如果我的两个分隔符在字符串中彼此相邻,它会在结果列表中放入一个空字符串。例如:在Python中使用多个分隔符分割字符串
re.split(',|;', "This,is;a,;string")
结果
['This', 'is', 'a', '', 'string']
有什么办法,以避免让我的列表中''
不添加,;
作为分隔符?
试试这个:
import re
re.split(r'[,;]+', 'This,is;a,;string')
> ['This', 'is', 'a', 'string']
嗯,还好。现在如果我的一个分隔符也是一个单词呢?例如:'re.split(',|; | string',“this,is; a,; string”)' –
然后这将工作:'re.split(r'[,;] + | string', 'This'is; a,; string')' –
现在输出结果为'['This','''''''''','']' –