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

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

问题描述

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

<预><代码>>>>s = "äåö">>>秒'xc3xa4xc3xa5xc3xb6'>>>印刷??

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

<预><代码>>>>s = ['äåö']>>>秒['xc3xa4xc3xa5xc3xb6']>>>印刷['xc3xa4xc3xa5xc3xb6']

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

<预><代码>>>>印刷['呸']

另外,如果字符串是 unicode 类型,你如何做和上面一样的事情?

<预><代码>>>>s = u'åäö'>>>秒你'xe5xe4xf6'>>>印刷奥>>>s = [u'åäö']>>>秒[u'xe5xe4xf6']>>>印刷[u'xe5xe4xf6']

解决方案

当你打印一个字符串时,你会得到对象的 __str__ 方法的输出 - 在这种情况下是不带引号的字符串.列表的 __str__ 方法不同,它创建一个包含开头和结尾 [] 的字符串,以及由列表的 __repr__ 方法生成的字符串.其中包含的每个对象.您看到的是 __str____repr__ 之间的区别.

您可以改为构建自己的字符串:

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

这个版本应该适用于 Python 2 中的 Unicode 和字节字符串:

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

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

>>> s = "äåö"
>>> s
'xc3xa4xc3xa5xc3xb6'
>>> print s
äåö

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

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

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
['äåö']

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

>>> s = u'åäö'
>>> s
u'xe5xe4xf6'
>>> print s
åäö
>>> s = [u'åäö']
>>> s
[u'xe5xe4xf6']
>>> print s
[u'xe5xe4xf6']

解决方案

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

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

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