Print a list that contains Chinese characters in Python

这一生的挚爱 提交于 2019-11-29 10:53:27

why did the last line get the correct output, and the others didn't?

When you print foo, what gets printed out is str(foo).

However, if foo is a list, str(foo) uses repr(bar) for each element bar, not str(bar).

The str of a string is the string itself; the repr of a string is the string inside quotes, and escaped.

how do I correct the wrong ones

If you want to print the str of every element in a list, you have to do that explicitly. For example:

print '[' + ', '.join(["asdf", "中文"]) + ']'

There have been sporadic proposals to change this behavior, so str on a sequence calls str on its members. PEP 3140 is the rejected proposal. This thread from 2009 explains the design rationale behind rejecting it.

But primarily, it's either so these don't print the same thing:

a = 'foo, bar'
b = 'foo'
c = 'bar'
print [a]
print [b, c]

Or, paraphrasing Ned Batchelder: repr is always for geeks; str is for humans when possible, but printing lists with their brackets and commas is already for geeks.

The first two are using the __repr__ of the strings, the last one is using the __str__ method

You could use

print ", ".join(["asdf", "中文"])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!