如何拆分字符串以保留标点符号? (Python)

时间:2020-02-11 18:50:11

标签: python string split

考虑到结果中的标点符号,如何在python中拆分字符串?

以下代码:

s = "Hello, my name is Robert."
s_splitted = s.split()

将给出输出:

["Hello,","my","name","is","Robert."]

如何获得以下结果?

["Hello",",","my","name","is","Robert","."]

2 个答案:

答案 0 :(得分:0)

正则表达式可以处理此问题。

import re

s = "Hello, my name is Robert."
s_splitted = [part for part in re.split(r'\b|\s', s) if part != '']
# ['Hello', ',', 'my', 'name', 'is', 'Robert']

答案 1 :(得分:0)

this回答您的问题吗?

所以在您的情况下:

import re

s = "Hello, my name is Robert."
items = re.findall(r"[\w']+|[.,!?;]", s)