python的format易混淆的细节
之前使用format特性将提示词模板进行了优化,但是优化后总是有字符串解析错误。我是通过固定模板,大模型回复成json格式的字符串,之后进行处理。加上了format后,大模型回复的就是单引号形式,而json处理要求双引号形式。经过调试,发现我使用format时会将双引号转为单引号:
content = """你好,我叫{name},今年{age}岁。
其他信息{other_info}"""
name = "glm"
age = 999
other_info = {"school":"AKU", "stu_id":2517123}
content = content.format(name=name,age=age,other_info=other_info)
print(content)
# 你好,我叫glm,今年999岁。
# 其他信息{'school': 'AKU', 'stu_id': 2517123}
在python中,会将双引号包裹的自动转为单引号。
因此,在这里要将other_info改成字符串形式:
content = """你好,我叫{name},今年{age}岁。
其他信息{other_info}"""
name = "glm"
age = 999
other_info = "{\"school\":\"AKU\", \"stu_id\":2517123}"
content = content.format(name=name,age=age,other_info=other_info)
print(content)
# 你好,我叫glm,今年999岁。
# 其他信息{"school":"AKU", "stu_id":2517123}