Search code examples
pythonstringpython-2.xstring-literals

Python string literal throwing errors with place holders


I have a list as : token_found = ["abcdxyz", "1234567"]

I have a multiline string as below:

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])

Now when I run the above code I expect that the place holders {0} and {1} to be replaced with the values abcdxyz and 1234567 respectively, unless I am doing something wrong and which I do not understand.

Contrary to my assumption, I am getting the below error: KeyError: "'type'"


Solution

  • curly brackets {, } should be doubled to print them literally:

    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)
    

    The output:

    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: