我在 python 中,我想在字符串中添加引号。具体来说,我有以下字符串:
'{name:robert,surname:paul}'
我想以编程方式获取以下内容,首先操作
'{name:"robert",surname:"paul"}'
有什么有效的方法可以做到这一点吗?
最佳答案
使用正则表达式匹配 :
之后的单词 \w*
并使用反向引用 \1
替换它:
在 regex
字符串前加上 r
(原始字符串)以自动转义字符。
import re
input_str='{name:robert,surname:paul}'
output_str=re.sub(r':(\w*)', r':"\1"', input_str )
print output_str
会产生
{name:"robert",surname:"paul"}
关于python - 在python中自动添加字符串内的引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47096806/