如何折叠连续的分隔符? [英] How to collapse consecutive delimiters?

查看:51
本文介绍了如何折叠连续的分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中默认的 split 方法将连续空格视为单个分隔符.但是如果你指定一个分隔符字符串,连续的分隔符不会折叠:

<预><代码>>>>'aaa'.split('a')['', '', '', '']

折叠连续分隔符最直接的方法是什么?我知道我可以从结果列表中删除空字符串:

<预><代码>>>>结果 = 'aaa'.split('a')>>>结果['', '', '', '']>>>result = [item for item in result if item]

但是有没有更方便的方法?

解决方案

您可以使用 re.split 用正则表达式作为分隔符,如:

re.split(pattern, string[, maxsplit=0, flags=0])

The default split method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are not collapsed:

>>> 'aaa'.split('a')
['', '', '', '']

What is the most straightforward way to collapse consecutive delimiters? I know I could just remove empty strings from the result list:

>>> result = 'aaa'.split('a')
>>> result
['', '', '', '']
>>> result = [item for item in result if item]

But is there a more convenient way?

解决方案

You can use re.split with a regular expression as the delimiter, as in:

re.split(pattern, string[, maxsplit=0, flags=0])

这篇关于如何折叠连续的分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆