【问题标题】:Python string literal throwing errors with place holders [duplicate]占位符的Python字符串文字抛出错误[重复]
【发布时间】:2018-04-15 22:43:36
【问题描述】:

我有一个列表: 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'"

【问题讨论】:

    标签: python string python-2.x string-literals


    【解决方案1】:

    大括号{} 应加倍以按字面意思打印:

    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:
    

    【讨论】:

    • 谢谢!我不知道这个。 :)
    • @qre0ct,不客气
    【解决方案2】:

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

    我记得 Escape 是双括号 {{

    【讨论】:

    • 是的,从上面罗曼的回答中得到。无论如何谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多