9

如果您有如下字符串,带有 unicode 字符,您可以打印它,并获得未转义的版本:

>>> s = "äåö"
>>> s
'\xc3\xa4\xc3\xa5\xc3\xb6'
>>> print s
äåö

但是如果我们有一个包含上面字符串的列表并打印它:

>>> s = ['äåö']
>>> s
['\xc3\xa4\xc3\xa5\xc3\xb6']
>>> print s
['\xc3\xa4\xc3\xa5\xc3\xb6']

您仍然会得到转义的字符序列。您如何才能使列表的内容不转义,这可能吗?像这样:

>>> print s
['äåö']

另外,如果字符串是unicode那种类型的,你怎么做和上面一样的呢?

>>> s = u'åäö'
>>> s
u'\xe5\xe4\xf6'
>>> print s
åäö
>>> s = [u'åäö']
>>> s
[u'\xe5\xe4\xf6']
>>> print s
[u'\xe5\xe4\xf6']
4

5 回答 5

9

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']'
于 2013-05-28T18:50:20.960 回答
8

这令人满意吗?

>>> s = ['äåö', 'äå']
>>> print "\n".join(s)
äåö
äå
>>> print ", ".join(s)
äåö, äå


>>> s = [u'åäö']
>>> print ",".join(s)
åäö
于 2013-05-28T18:24:21.307 回答
3

在 Python 2.x 中,默认值是您所遇到的:

>>> s = ['äåö']
>>> s
['\xc3\xa4\xc3\xa5\xc3\xb6']

但是,在 Python 3 中,它可以正确显示:

>>> s = ['äåö']
>>> s
['äåö']
于 2013-05-28T18:34:45.527 回答
0

另一种解决方案

s = ['äåö', 'äå']
encodedlist=', '.join(map(unicode, s))
print(u'[{}]'.format(encodedlist).encode('UTF-8'))

给出 [äåö, äå]

于 2015-04-08T21:19:44.757 回答
0

可以使用这个包装类:

#!/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}
于 2017-08-23T14:00:50.403 回答