用“("和“)"分割字符串;并保留分隔符(Python) [英] Split a string with "(" and ")" and keep the delimiters (Python)

查看:243
本文介绍了用“("和“)"分割字符串;并保留分隔符(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个字符串:

s = "123(45)678"

我怎样才能得到这个列表?

How can I can get this list?

l = ['123','(','45',')','678']

推荐答案

如果您只对 '(' or ')' 感兴趣,那么 str.partition 就足够了.

If you were only interested in '(' or ')' then str.partition would have been sufficient.

由于您有多个分隔符并且您想保留它们,您可以使用 re.split 带有捕获组:

Since you have multiple delimiters AND you want to keep them, you can use re.split with a capture group:

import re

s = "123(45)678"

print(re.split(r'([()])', s))
# ['123', '(', '45', ')', '678']

这篇关于用“("和“)"分割字符串;并保留分隔符(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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