为什么我会得到u"xyz"?在Python中打印unicode字符串列表时的格式? [英] Why do I get the u"xyz" format when I print a list of unicode strings in Python?

查看:104
本文介绍了为什么我会得到u"xyz"?在Python中打印unicode字符串列表时的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意以下行为:

a = u"foo"
b = u"b\xe1r"   # \xe1 is an 'a' with an accent
s = [a, b]

print a, b
print s
for x in s: print x,

结果是:

foo bár
[u'foo', u'b\xe1r']
foo bár

当我只打印变量ab中的两个值时,我得到了期望的结果;当我将字符串值放在列表中并打印时,会得到不需要的u"xyz"形式;最终,当我使用循环从列表中打印值时,我又得到了第一个表格.有人可以解释一下这种看似奇怪的行为吗?我知道可能有很好的理由.

When I just print the two values sitting in variables a and b, I get what I expect; when I put the string values in a list and print it, I get the unwanted u"xyz" form; finally, when I print values from the list with a loop, I get the first form again. Can someone please explain this seemingly odd behavior? I know there's probably a good reason.

推荐答案

打印列表时,您会得到每个元素的repr(),实际上并不是要打印列表,因此python会尝试打印具有代表性的内容它的结构.

When you print a list, you get the repr() of each element, lists aren't really meant to be printed, so python tries to print something representative of it's structure.

如果要以任何特定方式设置其格式,请明确说明其设置方式,或覆盖它的__repr__方法.

If you want to format it in any particular way, either be explicit about how you want it formatted, or override it's __repr__ method.

这篇关于为什么我会得到u"xyz"?在Python中打印unicode字符串列表时的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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