簡體   English   中英

如何在三引號中做 Python f 字符串

[英]How to do Python f strings in triple quotes

我正在嘗試在循環中編寫一個相當簡單的請求腳本,我需要將列表項作為參數之一傳入。 我已經閱讀並理解 f 字符串需要雙花括號而不是單花括號,但它仍然無法正常工作。

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

這給了我以下錯誤

ValueError: Invalid format specifier

我也試過使用 format(),如下:

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

但這給了我以下錯誤:

KeyError: '\n        "name"'

您需要{{在格式字符串中表示文字{ ,因此您的字符串應該看起來像

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

但是,無需自己生成 JSON。 如果您使用json關鍵字參數, requests將為您執行此操作:

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

試試這個:

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

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

在 for 循環中, values格式如下:


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

這就是你要找的嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM