Python - Unicode to ASCII conversion

前端 未结 2 2034
夕颜
夕颜 2020-11-29 08:30

I am unable to convert the following Unicode to ASCII without losing data:

u\'ABRA\\xc3O JOS\\xc9\'

I tried encode and d

2条回答
  •  广开言路
    2020-11-29 09:05

    I needed to calculate the MD5 hash of a unicode string received in HTTP request. MD5 was giving UnicodeEncodeError and python built-in encoding methods didn't work because it replaces the characters in the string with corresponding hex values for the characters thus changing the MD5 hash. So I came up with the following code, which keeps the string intact while converting from unicode.

    unicode_string = ''.join([chr(ord(x)) for x in unicode_string]).strip()
    

    This removes the unicode part from the string and keeps all the data intact.

提交回复
热议问题