且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用正则表达式在Python中将转义的双引号替换为单引号

更新时间:2023-02-21 13:41:33

此答案仅在我们交换的评论之后:

This answer is just following the comments we've exchanged:

import json
js = r'{"result":"{\"key\":\"How are you? \"Great!\" he said. \"Coffee ?\"\"},{\"key\":\" 2. \"Why not sure\". They walked away\"}"}'
data1 = json.loads(js)
s = data1['result']

good_characters = [":","{","}", ","]
result = "" 
for key, value in enumerate(s):
    if (value == "\"" and s[key-1] not in good_characters) and (value == "\"" and s[key+1] not in good_characters):
        result += '\''  
    else:
        result += value

print (result)

输出

{"key":"How are you? 'Great!' he said. 'Coffee ?'"},{"key":" 2. 'Why not sure'. They walked away"}