Print LIST of unicode chars without escape characters

后端 未结 5 877
南方客
南方客 2020-11-27 07:39

If you have a string as below, with unicode chars, you can print it, and get the unescaped version:

>>> s = \"äåö\"
>>> s
\'\\xc3\\xa4\\xc3         


        
5条回答
  •  -上瘾入骨i
    2020-11-27 08:16

    When you print a string, you get the output of the __str__ method of the object - in this case the string without quotes. The __str__ method of a list is different, it creates a string containing the opening and closing [] and the string produced by the __repr__ method of each object contained within. What you're seeing is the difference between __str__ and __repr__.

    You can build your own string instead:

    print '[' + ','.join("'" + str(x) + "'" for x in s) + ']'
    

    This version should work on both Unicode and byte strings in Python 2:

    print u'[' + u','.join(u"'" + unicode(x) + u"'" for x in s) + u']'
    

提交回复
热议问题