python - 在 Python 中,如何拆分字符串并保留分隔符?

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

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

这就是我想要的:

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

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

最佳答案

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

https://stackoverflow.com/questions/2136556/

相关文章:

linux - 如何将stderr和stdout重定向到脚本同一行中的不同文件?

linux - sed 中的环境变量替换

python - 为什么 Pycharm 的检查员提示 "d = {}"?

python - 如何根据任意条件函数过滤字典?

c - 如何将文件指针 ( FILE* fp ) 转换为文件描述符 (int fd)?

python - 使用 dict 文字和 dict 构造函数之间有区别吗?

python - 如何获得 Pandas 系列的元素逻辑非?

python - 类型错误 : method() takes 1 positional argume

linux - 查找不属于特定用户的文件

linux - 如何在 Ubuntu 上设置和运行 PhantomJS?