Python中,我该如何切分字符串后保留分割符?

原文来源:https://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators

问:
下面是最简单的解释:我是这么用的

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']
posted @ 2019-09-04 20:53  bingo彬哥  阅读(4015)  评论(0编辑  收藏  举报
本站总访问量