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

字符串比较空格问题:如何将空格替换为%20实现匹配

字符串空格转%20的实现方法

如果你需要将test1中的空格替换为%20,和test2进行相等性比较,有两种实用方法:

方法一:使用字符串replace方法

这是最直接的方式,专门针对空格做替换:

test1 = 'My Test'
test2 = 'My%20Test'

# 将test1中的空格替换为%20
converted_test1 = test1.replace(' ', '%20')

# 验证比较结果
print(converted_test1 == test2)  # 输出 True

方法二:使用URL编码工具函数

如果你的场景涉及URL相关的字符串处理,推荐使用Python标准库的urllib.parse.quote,它会按照URL编码规则处理所有不安全字符(不止空格):

from urllib.parse import quote

test1 = 'My Test'
test2 = 'My%20Test'

# 对test1进行URL编码
converted_test1 = quote(test1)

# 验证比较结果
print(converted_test1 == test2)  # 输出 True

两种方法都能实现需求,你可以根据实际场景选择:如果只需要替换空格,用replace更轻量;如果涉及其他特殊字符的编码,quote更专业。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:52:07