W3Schools Python环境中如何避免URL里的¬被替换为¬
问题描述
在W3Schools的Python环境中运行以下构建URL的代码时,输出的URL里¬ify片段中的¬被自动替换成了¬符号:
man_ids = ['1215', '1216', '1217'] a = 'https://DOMAINURL/cgi/editor.cgi?article=' z = '&context=STRUCTURELABEL¬ify_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
尝试使用原始字符串字面量无效,需要解决如何让代码输出完整的¬ify部分。
解决方法
方法1:对&进行转义
在字符串z中,把每个&替换成\&,避免环境将¬解析为特殊字符:
man_ids = ['1215', '1216', '1217'] a = 'https://DOMAINURL/cgi/editor.cgi?article=' z = '\&context=STRUCTURELABEL\¬ify_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参数拆分为单独的列表项,再通过&拼接,从根源避免¬连续字符出现:
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
相关产品推荐
相关产品推荐

