一、场景:
字符串str 本身含有字符{}时,对该字符串进行format 操作
二、方法
将非关键字符的{} 替换为{{}}
def index():
# 场景:
# str 是一个json字符串,通过format格式化对应value
# 由于format时,{}是关键字符,会和json字符串中的{}冲突,导致报错
# 此时,需要将json字符串中的{ }修改为{{ }}
str = """
{{
"code":"{}",
"language":"{}"
}}
"""
code = "print 'Hello World'"
language = "python"
# output:
# {
# "code":"print 'Hello World'",
# "language":"python"
# }
print(str.format(code, language))