您好,欢迎来到外链网!
当前位置:外链网 » 站长资讯 » 专业问答 » 文章详细 订阅RssFeed

Python 分割字符串时有多个分隔符怎么处理?

来源:互联网 浏览:94次 时间:2023-04-08

字符串方法str.split()帮助:

>>> help(str.split) Help on method_descriptor:split(self, /, sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. sep The delimiter according which to split vps云服务器 the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.>>>

用法: string.split( sep = None, maxsplit = -1)
string 要操作字符串
sep 分隔符,默认值为whitespace空白符
maxsplit 最大分割次数,默认值为-1,表示无限制

如果同时有多个分隔符怎么分割呢?
可以用循环多次分割来实现,例如:

>>> s = '6[5,12]3[2,6]1;35]67[8;9;11]12' >>> for j in '[],;':t=[i.split(j) for i in t]t=[i for j in t for i in j]>>> t ['6', '5', '12', '3', '2', '6', '1', '35', '67', '8', '9', '11', '12']>>>

懂正则表达式的可以一步到位:

>>> import re>>> s = '6[5,12]3[2,6]1;35]67[8;9;11]12'>>> re.split('\[|\]|,|;',s)['6', '5', '12', '3', '2', '6', '1', '35', '67', '8', '9', '11', '12']

注:竖线 | 是分隔符的分隔;也可用[]包括分隔符,[]中的不用竖线分开;两种方法都要注意转义符的使用。

>>> import re>>> s = '6[5,12]3[2,6]1;35]67[8;9;11]12'>>> re.split('[\[\],;]',s)['6', '5', '12', '3', '2', '6', '1', '35', '67', '8', '9', '11', '12']

64447465