Python中已包含花括号的字符串插值

2024-04-29 07:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个GraphQL查询字符串,我需要在字符串中插入三个变量,只有一个问题。GraphQL包含许多花括号,它干扰了Python f字符串的工作方式

number = 10
owner = "me"
name = "my_repo"
query = f"""
query {
    repository(owner:"{owner}", name:"{repo}") {
      pullRequests(first: {number}) {
        edges {
          node {
            state
            merged
            createdAt
          }
        }
      }
    }
  }
"""

上面的代码引发SyntaxError。所以我假设我需要完全使用f字符串? 当f字符串包含与插值无关的花括号时,有没有办法在Python中仍然使用f字符串?


Tags: 字符串namenumberrepositorymy方式repoquery