Python re.split()按char分割,但在分割文本中使用char

时间:2016-04-09 19:37:49

标签: python regex python-3.x

我在python中遇到了split函数的问题;当我尝试按{拆分文字时,文本会拆分,但{会被删除。

以下是一个例子:

s = "My=pet {looks a dog}, but he is=cat"

所需的输出是:

["My","=","pet","{","looks","a","dog","}",",","but","he","is","=","cat"]

2 个答案:

答案 0 :(得分:0)

使用re.findall更容易:

re.findall(r'[^\w\s]|\w+', s)

答案 1 :(得分:0)

默认的split()函数按空格分割。如果按字符或字符串拆分,它将使用该字符串或字符作为断点而不是数组的项。 在示例中,您可以在单词和字符之间添加空格。

s = "My = pet { looks a dog }, but he is = cat"
ans=s.split()
for item in ans:
  print ans

这将显示您询问的结果。