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

W3Schools Python环境中如何避免URL里的&not被替换为¬

问题描述

在W3Schools的Python环境中运行以下构建URL的代码时,输出的URL里&notify片段中的&not被自动替换成了¬符号:

man_ids = ['1215', '1216', '1217']
a = 'https://DOMAINURL/cgi/editor.cgi?article='
z = '&context=STRUCTURELABEL&notify_authors=0&window=abstract&withdraw_for_author=Withdraw+submission'

for x in man_ids:
    print(a + x + z)

实际输出示例:

https://DOMAINURL/cgi/editor.cgi?article=1215&context=STRUCTURELABEL¬ify_authors=0&window=abstract&withdraw_for_author=Withdraw+submission

尝试使用原始字符串字面量无效,需要解决如何让代码输出完整的&notify部分。

解决方法

方法1:对&进行转义

在字符串z中,把每个&替换成\&,避免环境将&not解析为特殊字符:

man_ids = ['1215', '1216', '1217']
a = 'https://DOMAINURL/cgi/editor.cgi?article='
z = '\&context=STRUCTURELABEL\&notify_authors=0\&window=abstract\&withdraw_for_author=Withdraw+submission'

for x in man_ids:
    print(a + x + z)

方法2:使用URL编码的&(即%26)

URL中&的标准编码形式是%26,直接替换字符串中的&为%26,输出的URL既符合规范,也不会被错误解析:

man_ids = ['1215', '1216', '1217']
a = 'https://DOMAINURL/cgi/editor.cgi?article='
z = '%26context=STRUCTURELABEL%26notify_authors=0%26window=abstract%26withdraw_for_author=Withdraw+submission'

for x in man_ids:
    print(a + x + z)

方法3:拆分参数拼接

将URL参数拆分为单独的列表项,再通过&拼接,从根源避免&not连续字符出现:

man_ids = ['1215', '1216', '1217']
base_url = 'https://DOMAINURL/cgi/editor.cgi?article={}'
params = [
    'context=STRUCTURELABEL',
    'notify_authors=0',
    'window=abstract',
    'withdraw_for_author=Withdraw+submission'
]

for man_id in man_ids:
    full_url = f"{base_url.format(man_id)}&{'&'.join(params)}"
    print(full_url)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:18:21