为什么Python 2的raw_input输出unicode字符串? [英] Why does Python 2's raw_input output unicode strings?
问题描述
hobbies = []
# Add your code below!
for i in range(3):
Hobby = str(raw_input("Enter a hobby:"))
hobbies.append(Hobby)
print hobbies
有了这个,它可以正常工作,但是如果我尝试的话,
With this, it works fine but if instead I try
Hobby = raw_input("Enter a hobby:")
我得到[u'Hobby1', u'Hobby2', u'Hobby3']
.额外的u
来自哪里?
I get [u'Hobby1', u'Hobby2', u'Hobby3']
. Where are the extra u
s coming from?
推荐答案
The question's subject line might be a bit misleading: Python 2's raw_input()
normally returns a byte string, NOT a Unicode string.
但是,如果它或sys.stdin
已被更改或替换(由应用程序或作为Python的替代实现的一部分),它可以返回Unicode字符串.
However, it could return a Unicode string if it or sys.stdin
has been altered or replaced (by an application, or as part of an alternative implementation of Python).
因此,我认为@ByteCommander的评论正确无误:
Therefore, I believe @ByteCommander is on the right track with his comment:
也许这与它所运行的控制台有关?
Maybe this has something to do with the console it's running in?
Codecademy使用的Python表面上是2.7,但是(a)通过使用
The Python used by Codecademy is ostensibly 2.7, but (a) it was implemented by compiling the Python interpreter to JavaScript using Emscripten and (b) it's running in the browser; so between those factors, there could very well be some string encoding and decoding injected by Codecademy that isn't present in plain-vanilla CPython.
注意:我自己没有使用Codecademy,也没有任何内部了解其内部工作原理.
Note: I have not used Codecademy myself nor do I have any inside knowledge of its inner workings.
这篇关于为什么Python 2的raw_input输出unicode字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!