[英]converting byte to str python2.7
I have a dictionary 我有一本字典
k ={'Creator': '\xfe\xff\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\xae\x00 \x00O\x00f\x00f\x00i\x00c\x00e\x00 \x00W\x00o\x00r\x00d\x00 \x002\x000\x000\x007'}
which is containing metadata of a pdf. 其中包含pdf的元数据。 In the pdf properties the Creator is Microsoft Office Word 2007. I am unable to convert
k['Creator']
to 'Microsoft Office Word 2007' as in this case. 在pdf属性中,创建者为Microsoft Office Word2007。在这种情况下,我无法将
k['Creator']
转换为“ Microsoft Office Word 2007”。
The data is encoded to UTF-16. 数据被编码为UTF-16。 Decode it:
解码:
print k['Creator'].decode('utf16')
This produces a unicode
value; 这将产生一个
unicode
值; your console may or may not be able to handle the non-ASCII ®
codepoint that includes. 您的控制台可能会也可能无法处理包含的非ASCII®
®
点。
Demo: 演示:
>>> k ={'Creator': '\xfe\xff\x00M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00\xae\x00 \x00O\x00f\x00f\x00i\x00c\x00e\x00 \x00W\x00o\x00r\x00d\x00 \x002\x000\x000\x007'}
>>> print k['Creator'].decode('utf16')
Microsoft® Office Word 2007
This gives the required string. 这给出了所需的字符串。
Code : 代码:
>>> print(k['Creator'].decode('utf16','ignore')).encode('utf-8')
Microsoft® Office Word 2007
>>> type((k['Creator'].decode('utf16','ignore')).encode('utf-8'))
<type 'str'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.