python coding utf-8_Python中的UTF-8编码

本文探讨了如何使用Python正确处理含有 '_ea_b4_80' 类型的UTF-8字符编码,通过实例说明了replace方法的局限,并提供了将字节转换为Unicode的正确方法。通过bytes.decode()实现编码转换,确保得到预期的中文字符'關'。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I have an UTF-8 character encoded with `_' in between, e.g., '_ea_b4_80'.

I'm trying to convert it into UTF-8 character using replace method, but I can't get the correct encoding.

This is a code example:

import sys

reload(sys)

sys.setdefaultencoding('utf8')

r = '_ea_b4_80'

r2 = '\xea\xb4\x80'

r = r.replace('_', '\\x')

print r

print r.encode("utf-8")

print r2

In this example, r is not the same as r2; this is an output.

\xea\xb4\x80

\xea\xb4\x80

관 <-- correctly shown

What might be wrong?

解决方案

\x is only meaningful in string literals, you're can't use replace to add it.

To get your desired result, convert to bytes, then decode:

import binascii

r = '_ea_b4_80'

rhexonly = r.replace('_', '') # Returns 'eab480'

rbytes = binascii.unhexlify(rhexonly) # Returns b'\xea\xb4\x80'

rtext = rbytes.decode('utf-8') # Returns '관' (unicode if Py2, str Py3)

print(rtext)

which should get you 관 as you desire.

If you're using modern Py3, you can avoid the import (assuming r is in fact a str; bytes.fromhex, unlike binascii.hexlify, only take str inputs, not bytes inputs) using the bytes.fromhex class method in place of binascii.unhexlify:

rbytes = bytes.fromhex(rhexonly) # Returns b'\xea\xb4\x80'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值