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

前端 未结 4 1338
栀梦
栀梦 2021-02-12 14:36

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 t

相关标签:
4条回答
  • 2021-02-12 14:57
    data="UTF-8 data"
    udata=data.decode("utf-8")
    data=udata.encode("latin-1","ignore")
    

    Should do it.

    0 讨论(0)
  • 2021-02-12 15:01

    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'
    
    0 讨论(0)
  • 2021-02-12 15:12

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

    0 讨论(0)
  • 2021-02-12 15:14

    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...

    0 讨论(0)
提交回复
热议问题