Python 带有占位符的字符串文字抛出错误

Python string literal throwing errors with place holders

我有一个列表: token_found = ["abcdxyz", "1234567"]

我有一个多行字符串如下:

user_creds_string = """
UserA_A:
    - name: 'Abcd'
      value: '{0}'
UserB_B:
    - name: 'Abcd'
      value: '{1}'
headers:
  - name: 'Abcd'
    value: 'Kota %(xyz)'
    inputs:
      apop: {'type':'hex-64', 'required': True} 
  - name: 'X-Broke'
    value: '%(BId) %(blahId)'
    inputs:
      UkID: {'type':'hex-16', 'required': True} 
      blahId: {'type':'hex-64', 'required': True} 
apis:
    """.format(token_found[0],token_found[1])

现在,当我 运行 上面的代码时,我希望占位符 {0}{1} 被替换为值 abcdxyz1234567分别,除非我做错了什么我不明白。

与我的假设相反,我收到以下错误: KeyError: "'type'"

您需要转义{format 看到模式 {'type' 并尝试在 formatkwargs 中查找 'type'

我记得转义是加倍大括号,{{

大括号 {} 应该加倍以按字面打印它们:

token_found = ["abcdxyz", "1234567"]
user_creds_string = """
UserA_A:
    - name: 'Abcd'
      value: '{0}'
UserB_B:
    - name: 'Abcd'
      value: '{1}'
headers:
  - name: 'Abcd'
    value: 'Kota %(xyz)'
    inputs:
      apop: {{'type':'hex-64', 'required': True}}
  - name: 'X-Broke'
    value: '%(BId) %(blahId)'
    inputs:
      UkID: {{'type':'hex-16', 'required': True}}
      blahId: {{'type':'hex-64', 'required': True}}
apis:
    """.format(token_found[0],token_found[1])

print(user_creds_string)

输出:

UserA_A:
    - name: 'Abcd'
      value: 'abcdxyz'
UserB_B:
    - name: 'Abcd'
      value: '1234567'
headers:
  - name: 'Abcd'
    value: 'Kota %(xyz)'
    inputs:
      apop: {'type':'hex-64', 'required': True}
  - name: 'X-Broke'
    value: '%(BId) %(blahId)'
    inputs:
      UkID: {'type':'hex-16', 'required': True}
      blahId: {'type':'hex-64', 'required': True}
apis: