在 Python 中,如何拆分字符串并保留分隔符? [英] In Python, how do I split a string and keep the separators?

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

问题描述

这是解释这一点的最简单方法.这是我正在使用的:

Here's the simplest way to explain this. Here's what I'm using:

re.split('\W', 'foo/bar spam\neggs')
-> ['foo', 'bar', 'spam', 'eggs']

这是我想要的:

someMethod('\W', 'foo/bar spam\neggs')
-> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']

原因是我想将一个字符串拆分为标记,对其进行操作,然后再将其重新组合在一起.

The reason is that I want to split a string into tokens, manipulate it, then put it back together again.

推荐答案

>>> re.split('(\W)', 'foo/bar spam\neggs')
['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']

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

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