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

如何在urllib.parse.quote_plus中使用通配符并解决格式字符报错

问题根因

你代码存在三个核心问题:

  • 执行顺序错误:先对带%s占位符的字符串做了URL编码,编码后%s里的%被转义为%25,后续replace操作无法匹配到目标占位符,导致替换失效
  • replace方法会返回新字符串,你没有将替换结果赋值给变量,操作不会生效
  • 遇到的ValueError: unsupported format character 'D'报错,是直接对包含特殊字符的连接串使用%格式化时,格式解析逻辑误识别占位符导致的。

正确实现方案

必须遵循「先替换占位符,后做URL编码」的执行顺序,不要搞反

方案1:先替换占位符再编码(简单直接)

import urllib.parse

user_email = 'my_email@xd.com'
# 第一步:先完成占位符替换
raw_conn_str = "Driver={ODBC Driver 17 for SQL Server};Server=tcp:dbhere.database.windows.net,1433;Database=dbhere;Uid=%s;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=15;Authentication=ActiveDirectoryIntegrated" % user_email
# 第二步:对替换完成的字符串做编码
params = urllib.parse.quote_plus(raw_conn_str)

方案2:用字符串模板避免格式化冲突(更稳妥)

如果你的连接串后续可能包含百分号字符,推荐用string.Template实现占位符替换,完全不会和%格式符号产生冲突:

import urllib.parse
from string import Template

user_email = 'my_email@xd.com'
# 定义$开头的模板占位符
conn_template = Template("Driver={ODBC Driver 17 for SQL Server};Server=tcp:dbhere.database.windows.net,1433;Database=dbhere;Uid=$user_email;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=15;Authentication=ActiveDirectoryIntegrated")
# 替换占位符
raw_conn_str = conn_template.substitute(user_email=user_email)
# 编码
params = urllib.parse.quote_plus(raw_conn_str)

两种方案执行后,params中的Uid字段就会被正确替换为你的邮箱地址,不会再出现%s残留的问题,也不会触发格式化报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:54:03