Python转码问题求助,字典字符串类型转换失败源码如何修改,python问题求助,#coding=utf-


#coding=utf-8x={'123':"我"}print x['123']print x['123'].decode("utf-8")name=str(x).split("'")[3]print nameprint name.decode("utf-8")

x = {'123': "我"}

此时utf8编码下,x为{'123': '\xe6\x88\x91'}

x是字典,作str(x)得到"{'123': '\\xe6\\x88\\x91'}"

str(x).split("'")得到['{', '123', ': ', '\\xe6\\x88\\x91', '}']

python解释器允许交互式打印,过程中可以清楚看见字典__str__()方法的实现

Solution 1

a =[i for i in x['123']]print b"".join(a).decode('utf-8')

Solution 2

print name.replace('\\x','').decode('hex').decode('utf-8')

Solution2,
1. 把name stringfy之後變成'\\xe6\\x88\\x91'
2. 移除\x變成'e68891'
3. decode成為hex
4. 再變成'utf-8'
5. print出來.

x['123'] = x['123'].decode("utf-8")

编橙之家文章,

评论关闭