Python to show special characters

前端 未结 3 1344
北荒
北荒 2020-12-18 07:28

I know there are tons of threads regarding this issue but I have not managed to find one which solves my problem.

I am trying to print a string but when printed it d

3条回答
  •  有刺的猬
    2020-12-18 07:58

    Unicode support in many languages is confusing, so your error here is understandable. Those strings are UTF-8 bytes, which would work properly if you drop the u at the front:

    >>> err = u'\xc3\x96berg'
    >>> print err
    Ã?berg
    >>> x = '\xc3\x96berg'
    >>> print x
    Öberg
    >>> u = x.decode('utf-8')
    >>> u
    u'\xd6berg'
    >>> print u
    Öberg
    

    For lots more information:

    http://www.joelonsoftware.com/articles/Unicode.html

    http://docs.python.org/howto/unicode.html


    You should really really read those links and understand what is going on before proceeding. If, however, you absolutely need to have something that works today, you can use this horrible hack that I am embarrassed to post publicly:

    def convert_fake_unicode_to_real_unicode(string):
        return ''.join(map(chr, map(ord, string))).decode('utf-8')
    

提交回复
热议问题