Python:如何在字符串拆分中包含分隔符? [英] Python: How can I include the delimiter(s) in a string split?

查看:44
本文介绍了Python:如何在字符串拆分中包含分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用多个分隔符分割一个字符串,但将分隔符保留在结果列表中.我认为这是解析任何类型公式的第一步很有用,我怀疑有一个很好的 Python 解决方案.

有人在 Java 中问过类似的问题 此处.

例如,典型的拆分如下所示:

<预><代码>>>>s='(二加三)加四'>>>s.split(f, '加')['(二','三)','四']

但我正在寻找一种将加号重新添加(或保留)的好方法:

['(二','加','三)','加','四']

最终我想为每个运算符和括号执行此操作,因此如果有办法获得

['(', '二', '加', '三', ')', '加', '四']

一次性完成,然后更好.

解决方案

你可以用 Python 的 re 模块做到这一点.

导入重新s='(二加三)加四'列表(过滤器(无,re.split(r(加| [()])",s)))

如果你只需要一个迭代器,你可以省略这个列表.

I would like to split a string, with multiple delimiters, but keep the delimiters in the resulting list. I think this is a useful thing to do an an initial step of parsing any kind of formula, and I suspect there is a nice Python solution.

Someone asked a similar question in Java here.

For example, a typical split looks like this:

>>> s='(twoplusthree)plusfour'
>>> s.split(f, 'plus')
['(two', 'three)', 'four']

But I'm looking for a nice way to add the plus back in (or retain it):

['(two', 'plus', 'three)', 'plus', 'four']

Ultimately I'd like to do this for each operator and bracket, so if there's a way to get

['(', 'two', 'plus', 'three', ')', 'plus', 'four']

all in one go, then all the better.

解决方案

You can do that with Python's re module.

import re
s='(twoplusthree)plusfour'
list(filter(None, re.split(r"(plus|[()])", s)))

You can leave out the list if you only need an iterator.

这篇关于Python:如何在字符串拆分中包含分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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