Python: convert string from UTF-8 to Latin-1

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

I feel stacked here trying to change encodings with Python 2.5

I have XML response, which I encode to UTF-8: response.encode('utf-8'). That is fine, but the program which uses this info doesn't like this encoding and I have to convert it to other code page. Real example is that I use ghostscript python module to embed pdfmark data to a PDF file - end result is with wrong characters in Acrobat.

I've done numerous combinations with .encode() and .decode() between 'utf-8' and 'latin-1' and it drives me crazy as I can't output correct result.

If I output the string to a file with .encode('utf-8') and then convert this file from UTF-8 to CP1252 (aka latin-1) with i.e. iconv.exe and embed the data everything is fine.

Basically can someone help me convert i.e. character á which is UTF-8 encoded as hex: C3 A1 to latin-1 as hex: E1?

Thanks in advance

回答1:

Instead of .encode('utf-8'), use .encode('latin-1').



回答2:

data="UTF-8 data" udata=data.decode("utf-8") data=udata.encode("latin-1","ignore") 

Should do it.



回答3:

Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:

>>> a = u"\u00E1" >>> type(a) <type 'unicode'> >>> a.encode('utf-8') '\xc3\xa1' >>> a.encode('latin-1') '\xe1' 


回答4:

If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.

In my case, I was using json.load on data incorrectly read from file by not using the encoding="utf-8". Trying to de-/encode the resulting string to latin-1 just does not help...



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!