在python中自动添加字符串内的引号

Uld*_*tre 3 python regex string

我在python中,我想在字符串中添加引号.具体来说,我有以下字符串:

'{name:robert,surname:paul}'
Run Code Online (Sandbox Code Playgroud)

我想以编程方式获得以下内容,在第一个上运行

'{name:"robert",surname:"paul"}'
Run Code Online (Sandbox Code Playgroud)

有没有有效的方法来执行此操作?

Ind*_*ent 8

使用正则表达式匹配单词\w*后面:并使用反向引用替换它\1:

前缀您regex的字符串r(原始字符串)来自动转义字符.

https://repl.it/Nh29/1

import re

input_str='{name:robert,surname:paul}'

output_str=re.sub(r':(\w*)', r':"\1"', input_str )

print output_str
Run Code Online (Sandbox Code Playgroud)

会产生

{name:"robert",surname:"paul"}
Run Code Online (Sandbox Code Playgroud)