You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python多行字符串中嵌入变量并保留格式?

解决多行字符串嵌入动态变量并保留格式的问题

针对你的需求,有几种简单可行的方案:

方案1:f-string + 三重引号

直接在三重引号前添加f前缀,将需要替换的变量用{}包裹即可,既能保留多行格式,也无需额外转义(仅当字符串本身需要保留{}时,才用{{}}转义)。

示例代码:

first_count = 5000
query = f'''
{{
   students(first: {first_count}) {{
      id
      firstName
      college {{
         id
         name
         location
         rating
      }}
   }}
}}
'''

注意:GraphQL查询本身包含大量{},而f-string会将{}识别为变量占位符,因此需要把查询中原有的{}写成{{}}转义,最终生成的字符串会保留单个{}。

方案2:str.format() 方法

如果不习惯f-string的写法,可使用传统的str.format(),在字符串中用占位符标记变量位置,再传入对应参数:

示例代码:

first_count = 5000
query = '''
{
   students(first: {count}) {
      id
      firstName
      college {
         id
         name
         location
         rating
      }
   }
}
'''.format(count=first_count)

该方案中,查询原本的{}无需转义,只有标记了占位符的{count}会被替换,其余{}直接保留。

方案3:使用模板字符串(string.Template)

若要避免和GraphQL的{}产生冲突,可使用标准库的string.Template,用$标记变量:

示例代码:

from string import Template

first_count = 5000
query_template = Template('''
{
   students(first: $count) {
      id
      firstName
      college {
         id
         name
         location
         rating
      }
   }
}
''')
query = query_template.substitute(count=first_count)

这种方式规则清晰,适合复杂模板场景,完全不会和原有语法冲突。

内容的提问来源于stack exchange,提问作者winterlyrock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:52:03