Python 字符串格式化和传递

Python 字符串格式化和传递,python,python-3.x,string,list,formatting,Python,Python 3.x,String,List,Formatting,我试图格式化下面的代码,但失败了,格式化函数无法工作,因为大括号已经就位 def in_list(line): input = '{"word1":["one"], "word_list":{}, "bool":true}'.format(line) print(input) msg = ["hello", "how", "are", "you"] in_list(msg) Expected Output: '{"word1":["one"], "word_list":["he

我试图格式化下面的代码,但失败了,格式化函数无法工作,因为大括号已经就位

def in_list(line):
  input = '{"word1":["one"], "word_list":{}, "bool":true}'.format(line)
  print(input)

msg = ["hello", "how", "are", "you"]
in_list(msg)



Expected Output:

'{"word1":["one"], "word_list":["hello","how","are","you"], "bool":true}'

有没有办法把这张单子传到句子里去。请让我知道,谢谢。

您必须将括号加倍
{{
}

从:

格式字符串包含由大括号包围的“替换字段” {}. 大括号中不包含的任何内容都被视为文字 文本,该文本将原封不动地复制到输出中。如果你需要包括 文本中的大括号字符,可以通过加倍进行转义: {{和}}

您可以使用:

def in_list(line):
    my_input = '{{"word1":["one"], "word_list":{0}, "bool":true}}'.format(line)
    print(my_input)

msg = ["hello","how","are","you"]
in_list(msg)

# {"word1":["one"], "word_list":['hello', 'how', 'are', 'you'], "bool":true}