打印没有转义字符的unicode字符列表 [英] Print LIST of unicode chars without escape characters

查看:140
本文介绍了打印没有转义字符的unicode字符列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

but if we have a list containing the string above and print it:

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

您仍然获得转义的字符序列。如何获得列表的内容未被转义,是否可能?像这样:

You still get escaped character sequences. How do you go about to get the content of the list unescaped, is it possible? Like this:

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

另外,如果字符串是 unicode 类型,你如何去做同样的事情?

Also, if the strings are of the unicode type, how do you go about doing the same as above?

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


推荐答案

当您打印字符串时,您将获得对象的 __ str __ 方法的输出 - 在这种情况下,不带引号的字符串。列表的 __ str __ 方法不同,它创建一个包含打开和关闭 [] 的字符串,并生成字符串通过包含在其中的每个对象的 __ repr __ 方法。你看到的是 __ str __ __ repr __ 之间的区别。

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) + ']'

在Python 2中的Unicode和字节字符串上工作:

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']'

这篇关于打印没有转义字符的unicode字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆