在Python中使用多个分隔符分割字符串 [英] Splitting a string with multiple delimiters in Python
本文介绍了在Python中使用多个分隔符分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用正则表达式使用多个分隔符来分割字符串。但是,如果我的两个定界符在字符串中彼此相邻出现,它将在结果列表中放置一个空字符串。例如:
I'm using regular expressions to split a string using multiple delimiters. But if two of my delimiters occur next to each other in the string, it puts an empty string in the resulting list. For example:
re.split(',|;', "This,is;a,;string")
结果
['This', 'is', 'a', '', 'string']
是否可以避免在不添加 ;;
作为分隔符的情况下在列表中获得''? p>
Is there any way to avoid getting ''
in my list without adding ,;
as a delimiter?
推荐答案
尝试一下:
import re
re.split(r'[,;]+', 'This,is;a,;string')
> ['This', 'is', 'a', 'string']
这篇关于在Python中使用多个分隔符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文