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

Python中能否在三重单引号(''')内部直接使用变量?

普通三重单引号字符串本身不支持直接识别{变量名}格式的占位符来调用变量,你示例的写法运行后会直接输出hello {friend},不会替换成对应变量值。

如果要实现你想要的变量替换效果,常用有以下几种方案:

  • 方案1:使用f-string(Python3.6及以上版本支持,最简洁)
    只需要在三重单引号前加f前缀即可,示例代码:
friend = 'Jake'
pnt = f'''
hello {friend}
'''
print(pnt) 

运行后输出内容为:

hello Jake
  • 方案2:使用str.format()方法
    如果需要后续动态替换参数、或者使用的Python版本低于3.6,可以用这个方案:
friend = 'Jake'
pnt = '''
hello {friend}
'''
print(pnt.format(friend=friend))
  • 方案3:使用%格式化符(旧版兼容写法)
    这是Python更早版本就支持的字符串格式化语法,现在使用场景较少:
friend = 'Jake'
pnt = '''
hello %s
'''
print(pnt % friend)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:36:03