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

Python中Unicode字符编码方法及Python 2 URL适配编码方案咨询

关于Python中Unicode编码的问题解答

1. 如何在Python中对Unicode字符进行编码?

Python 2和Python 3的处理逻辑不太一样,得分开说:

  • Python 3:字符串默认就是Unicode类型,直接调用encode()方法就能把它转成指定编码的字节串。比如转成最常用的UTF-8:

    # 定义Unicode字符串
    unicode_str = "你好,世界"
    # 编码为UTF-8字节串
    utf8_bytes = unicode_str.encode('utf-8')
    print(utf8_bytes)  # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
    
  • Python 2:默认字符串是字节串(str类型),要处理Unicode得先转成unicode类型——要么给字符串加u前缀,要么用unicode()函数转换,之后再调用encode():

    # 方式1:直接定义Unicode字符串
    unicode_str = u"你好,世界"
    utf8_bytes = unicode_str.encode('utf-8')
    
    # 方式2:从字节串转Unicode再编码
    str_bytes = "你好,世界"  # 假设这个字节串本身是UTF-8编码的
    unicode_str = unicode(str_bytes, 'utf-8')
    utf8_bytes = unicode_str.encode('utf-8')
    

2. Python 2中如何将Unicode编码为URL传输格式?

当然有对应的方法!URL传输需要的是百分号编码(Percent-Encoding),Python 2里用urllib模块就能搞定,核心步骤是:先把Unicode转成UTF-8字节串,再做URL编码。

单个字符串的编码

用urllib.quote()方法:

import urllib

unicode_str = u"你好,世界"
# 先转成UTF-8字节串,再做URL编码
url_encoded = urllib.quote(unicode_str.encode('utf-8'))
print(url_encoded)  # 输出: %E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C

多键值对的URL参数编码

用urllib.urlencode()方法,注意每个参数值都要转成UTF-8字节串:

import urllib

params = {
    'name': u"张三",
    'message': u"Hello,世界"
}
# 遍历字典,把每个Unicode值转成UTF-8再编码
encoded_params = urllib.urlencode({k: v.encode('utf-8') for k, v in params.items()})
print(encoded_params)  # 输出: name=%E5%BC%A0%E4%B8%89&message=Hello%EF%BC%8C%E4%B8%96%E7%95%8C

这里要踩个Python 2的坑:绝对不能直接对unicode类型调用urllib.quote(),一定会报错,必须先转成字节串再处理。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:41:36