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

在Python字符串中插入HTML标签遇问题,寻求解决方法

解决Python字符串中插入HTML标签的问题

你的代码无法得到预期结果的核心原因是误用了HTML实体转义序列(<、"),导致生成的不是可解析的HTML标签,而是纯文本格式的转义字符。以下是两种可行的解决方案:

方案1:使用str.format()修正写法

直接在三重双引号字符串中写入真实的HTML标签,Python的三重双引号可以直接容纳双引号,无需转义:

# 定义变量示例
report = "月度销售报告"
ds_link = "https://your-report-link.com"

body = """
  Dear sender,

  Please find below the link of the report {}.
  
  <a href="{}">{}</a>

  As usual this report was generated automatically and was not validated afterwards.
  Any question or issue regarding this report should be addressed to x.

  Regards,
  Analytics Team
""".format(report, ds_link, report)

方案2:使用f-string(Python 3.6+推荐)

f-string语法更直观,直接在字符串中嵌入变量,代码可读性更高:

# 定义变量示例
report = "月度销售报告"
ds_link = "https://your-report-link.com"

body = f"""
  Dear sender,

  Please find below the link of the report {report}.
  
  <a href="{ds_link}">{report}</a>

  As usual this report was generated automatically and was not validated afterwards.
  Any question or issue regarding this report should be addressed to x.

  Regards,
  Analytics Team
"""

两种方案生成的body字符串都会包含有效的HTML链接标签,能够被HTML解析器正确识别为可点击的链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:15:35