python编程输出汉字

编程入门 行业动态 更新时间:2024-10-14 10:41:44

python编程输出<a href=https://www.elefans.com/category/jswz/34/1769833.html style=汉字"/>

python编程输出汉字

My code looks like :

# -*- coding: utf-8 -*-

print ["asdf", "中文"]

print ["中文"]

print "中文"

The output in the Eclipse console is very strange:

['asdf', '\xe4\xb8\xad\xe6\x96\x87']

['\xe4\xb8\xad\xe6\x96\x87']

中文

My first question is: why did the last line get the correct output, and the others didn't?

And my second question is: how do I correct the wrong ones (to make them output real characters instead of the code that begins with "x") ?

Thank you guys!!

解决方案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.

更多推荐

python编程输出汉字

本文发布于:2024-03-04 03:01:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1708093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:汉字   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!