Print LIST of unicode chars without escape characters

后端 未结 5 880
南方客
南方客 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条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 08:24

    One can use this wrapper class:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    class ReprToStrString(str):
        def __repr__(self):
            return "'" + self.__str__() + "'"
    
    
    class ReprToStr(object):
        def __init__(self, printable):
            if isinstance(printable, str):
                self._printable = ReprToStrString(printable)
            elif isinstance(printable, list):
                self._printable = list([ReprToStr(item) for item in printable])
            elif isinstance(printable, dict):
                self._printable = dict(
                    [(ReprToStr(key), ReprToStr(value)) for (key, value) in printable.items()])
            else:
                self._printable = printable
    
        def __repr__(self):
            return self._printable.__repr__()
    
    
    russian1 = ['Валенки', 'Матрёшка']
    print russian1
    # Output:
    # ['\xd0\x92\xd0\xb0\xd0\xbb\xd0\xb5\xd0\xbd\xd0\xba\xd0\xb8', '\xd0\x9c\xd0\xb0\xd1\x82\xd1\x80\xd1\x91\xd1\x88\xd0\xba\xd0\xb0']
    print ReprToStr(russian1)
    # Output:
    # ['Валенки', 'Матрёшка']
    
    
    russian2 = {'Валенки': 145, 'Матрёшка': 100500}
    print russian2
    # Output:
    # {'\xd0\x92\xd0\xb0\xd0\xbb\xd0\xb5\xd0\xbd\xd0\xba\xd0\xb8': 145, '\xd0\x9c\xd0\xb0\xd1\x82\xd1\x80\xd1\x91\xd1\x88\xd0\xba\xd0\xb0': 100500}
    print ReprToStr(russian2)
    # Output:
    # {'Матрёшка': 100500, 'Валенки': 145}
    

提交回复
热议问题