How do I convert a unicode to a string at the Python level?

后端 未结 7 1347
刺人心
刺人心 2020-12-09 17:56

The following unicode and string can exist on their own if defined explicitly:

>>> value_str=\'Andr\\xc3\\xa9\'
>>> value_uni=u\'Andr\\xc3\         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 18:36

    The OP is not converting to ascii nor utf-8. That's why the suggested encode methods won't work. Try this:

    v = u'Andr\xc3\xa9'
    s = ''.join(map(lambda x: chr(ord(x)),v))
    

    The chr(ord(x)) business gets the numeric value of the unicode character (which better fit in one byte for your application), and the ''.join call is an idiom that converts a list of ints back to an ordinary string. No doubt there is a more elegant way.

提交回复
热议问题