【问题标题】:String Formating and Passing字符串格式化和解析
【发布时间】:2020-04-20 15:31:33
【问题描述】:

我正在尝试格式化下面的代码,但它失败了,因为大括号已经到位,所以格式化功能不起作用。

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}'

有没有办法将列表传递到句子中。请告诉我,谢谢。

【问题讨论】:

    标签: python python-3.x string list formatting


    【解决方案1】:

    您必须将括号 {{}} 加倍

    来自docs

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

    你可以使用:

    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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-10
      • 2019-06-23
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多