【问题标题】:Why does Python 2's raw_input output unicode strings?为什么 Python 2 的 raw_input 输出 unicode 字符串?
【发布时间】:2016-08-19 17:57:57
【问题描述】:

我在Codecademy's Python lesson上尝试了以下操作

hobbies = []

# Add your code below!
for i in range(3):
    Hobby = str(raw_input("Enter a hobby:"))
    hobbies.append(Hobby)

print hobbies

有了这个,它工作正常,但如果我尝试

Hobby = raw_input("Enter a hobby:")

我收到[u'Hobby1', u'Hobby2', u'Hobby3']。额外的us 来自哪里?

【问题讨论】:

  • Python string prints as [u'String'] 或许你可以在这里找到答案。
  • 您使用的是哪个版本的 Python?我在 Python 2.7 中都收到了相同的信息。 u 表示Unicode 编码。
  • 也许这与它运行的控制台有关?
  • 我使用了 CodeAcademy 的 Web 控制台。我认为它运行 2.7
  • @KIDJourney 它不是重复的:“为什么 raw_input() 返回 Unicode”(虽然它应该在 Python 2 上返回字节字符串)与“为什么打印包含 Unicode 字符串的列表会产生 @ 987654330@".

标签: python input unicode python-2.x


【解决方案1】:

'u' 表示它是一个 unicode。您还可以指定raw_input().encode('utf8') 转换为字符串。

编辑: 我在 python 2.7 中检查它返回字节字符串而不是 unicode 字符串。所以问题在这里是别的东西。

编辑: 如果 sys.stdin.encoding 是 unicode,则 raw_input() 返回 unicode。

在 codeacademy python 环境中,sys.stdin.encoding 和 sys.stdout.decoding 都是 none,默认 endcoding 方案是 ascii。

只有在无法从环境中找到合适的编码方案时,Python 才会使用此默认编码。

【讨论】:

  • raw_input() 在 Python 2.X 中返回字节字符串,而不是 Unicode 字符串。其他事情正在发生。
  • @MarkTolonen:在 Python 3 上没有 raw_input(),因此可以肯定地说,raw_input() 总是返回一个字节串,除非像 win-unicode-console 这样的第三方模块覆盖了它的行为。
  • @J.F.Sebastian 我确实说过raw_input 重新运行一个字节字符串。你想说什么?回答者说反了。
  • @MarkTolonen 你说 "raw_input() in Python 2.X 返回字节字符串" 这可以解释为它在 Python 3 上的行为不同。我说的是 " Python 3" 上没有 raw_input() 来消除歧义。我同意你的看法,我的评论只是一个补充。
  • 这里的要点是这个答案提供了明显不正确的信息。 :( 我知道它可以被接受,即使它是错误的,因为提问者不知道更好。但是它是如何获得多个赞成票的?
【解决方案2】:

您可以在将字符串附加到列表之前对其进行编码:

hobbies = []

# Add your code below!
for i in range(3):
    Hobby = raw_input("Enter a hobby:")
    hobbies.append(Hobby.encode('utf-8')

print hobbies

【讨论】:

  • 在这种情况下,编码是不必要的。仅当第一行没有 str() 开头时才需要它
【解决方案3】:

问题的主题行可能有点误导:Python 2 的 raw_input() 通常返回字节字符串,而不是 Unicode 字符串。

但是,如果它或sys.stdin 已被更改或替换(被应用程序或作为 Python 的替代实现的一部分),它可能返回一个 Unicode 字符串。

因此,我相信@ByteCommander 的评论是正确的:

也许这与它运行的控制台有关?

Codecademy 使用的 Python 表面上是 2.7,但 (a) 它是通过使用 Emscripten 将 Python 解释器编译为 JavaScript 来实现的,并且 (b) 它在浏览器中运行;所以在这些因素之间,很可能有一些由 Codecademy 注入的字符串编码和解码,而这些字符串编码和解码在普通 CPython 中是不存在的。

注意:我自己没有使用过 Codecademy,也不了解它的内部工作原理。

【讨论】:

  • 只想说这几乎是肯定的。我来寻找一个通用的答案,它是 1000%,因为我在 Codecademy Python 2.7 课程中处于越野状态。这一定是他们的目的。很高兴知道默认行为是合乎逻辑的。
【解决方案4】:

额外的us 来自哪里?

  • raw_input() 在您的环境中返回 Unicode 字符串
  • repr() 如果您打印列表中的每个项目,则会调用它(转换为字符串)
  • Unicode 字符串的文本表示 (repr()) 与 Python 中的 Unicode 文字相同:u'abc'

这就是为什么print [raw_input()] 可能会产生:[u'abc']

您在第一个代码示例中看不到 u'',因为 str(unicode_string) 调用了 unicode_string.encode(sys.getdefaultencoding()) 的等价物,即它将 Unicode 字符串转换为字节字符串——除非您是认真的,否则不要这样做。

raw_input()可以返回unicode吗?

Yes:

#!/usr/bin/env python2
"""Demonstrate that raw_input() can return Unicode."""
import sys

class UnicodeFile:
    def readline(self, n=-1):
        return u'\N{SNOWMAN}'

sys.stdin = UnicodeFile()
s = raw_input()
print type(s)
print s

输出:

<type 'unicode'>
☃

实际示例是win-unicode-console 包,它可以替换raw_input() 以支持在Windows 上输入超出控制台代码页范围的Unicode 字符。相关:这里是why sys.stdout should be replaced

可能raw_input()返回unicode

是的。

raw_input() is documented to return a string:

该函数然后从输入中读取一行,并将其转换为 字符串 (去除尾随的换行符),然后返回。

String 在 Python 2 中是字节字符串或 Unicode 字符串:isinstance(s, basestring)

raw_input() 的 CPython 实现明确支持 Unicode 字符串:builtin_raw_input() can call PyFile_GetLine()PyFile_GetLine() considers bytestrings and Unicode strings to be strings—it raises TypeError("object.readline() returned non-string") otherwise

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2011-03-11
    • 2015-05-20
    相关资源
    最近更新 更多