Skip to main content
 首页 » 编程设计

python之如何使用 python 将 utf-8 字符串转换为 big5

2025年05月04日12jillzhang

我使用 Python 2.6.6 我的语言环境是 ('en_US', 'UTF8')

我尝试了很多方法将 utf-8 字符串转换为 big5,但都行不通。 如果您知道该怎么做,请给我一些建议,非常感谢。


“单车”的中文意思是“自行车”

它的unicode是\u55ae\u8eca

str_a = u'\u55ae\u8eca' 
str_b = '\u55ae\u8eca' 
print str_a    # output '單車' 
print str_b    # output '\u55ae\u8eca' 

我知道 str_a 可以工作,但我也想将 str_b 转换为 big5。

我试过decode、encode、unicode,还是不行。

有什么好主意吗?谢谢。

请您参考如下方法:

str_b 是一个字节序列:

In [19]: list(str_b) 
Out[19]: ['\\', 'u', '5', '5', 'a', 'e', '\\', 'u', '8', 'e', 'c', 'a'] 

反斜杠和u 等等都只是单独的字符。将其与 unicode 对象 str_a 中的 unicode 代码点序列进行比较:

In [24]: list(str_a) 
Out[24]: [u'\u55ae', u'\u8eca'] 

使用 unicode-escape 将格式错误的字符串 str_b 转换为 unicode 解码:

In [20]: str_b.decode('unicode-escape') 
Out[20]: u'\u55ae\u8eca' 
 
In [21]: print(str_b.decode('unicode-escape')) 
單車