Aerandir
Aerandir

Reputation: 127

How to do Python f strings in triple quotes

I'm trying to write a fairly simple requests script in a loop, which I need to pass the list item in as one of the parameters. I've done some reading and understand that f strings require double curly braces instead of single, but it's still not working.

import requests

org_names = ['name 1', 'name 2']

for name in org_names:
    values = f"""
      {
        "name": "{{name}}",
        "groupId": "xxxx"
      }
    """

    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'xxxxx'
    }

    response = requests.post('https://xxxx', data=values, headers=headers)

    data = response.json()

This gives me the following error

ValueError: Invalid format specifier

I've also tried using format(), as follows:

for name in org_names:
    values = """
      {
        "name": "{{}}",
        "groupId": "xxxx"
      }
    """.format(name)

but this gives me the following error:

KeyError: '\n        "name"'

Upvotes: 6

Views: 10039

Answers (2)

Seraph
Seraph

Reputation: 444

Try this:

org_names = ['name 1', 'name 2']

for name in org_names:
    values = f'''
      {{
        name: "{name}",
        groupId: "xxxx",
      }}
   '''

values will be formatted like the following in the for loop:


      {
        name: "name 1",
        groupId: "xxxx",
      }    

Is that what you are looking for?

Upvotes: 0

chepner
chepner

Reputation: 531055

You need {{ in a format string to represent a literal {, so your string should look like

values = f"""
  {{
    "name": "{name}",
    "groupId": "xxxx"
  }}
"""

However, there is no need to generate JSON yourself. requests will do that for you if you use the json keyword argument:

 response = requests.post('https://xxxx',
                          json={'name': name, 'groupId': 'xxxx'},
                          headers=headers)

Upvotes: 7

Related Questions