python - 无法将度数符号输入 raw_input

标签 python python-2.7 character-encoding python-unicode

我的代码中的问题看起来像这样:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

deg = u'°'
print deg
print '40%s N, 100%s W' % (deg, deg)
codelim = raw_input('40%s N, 100%s W)? ' % (deg, deg))

我正在尝试为纬度/经度字符串中的定界符生成一个 raw_input 提示,该提示应该包含此类字符串的示例。 print degprint '40%s N, 100%s W' % (deg, deg) 都工作正常——它们返回“°”和“40° N” , 100° W"——但 raw_input 步骤每次都失败。我得到的错误如下:

Traceback (most recent call last):
  File "C:\Users\[rest of the path]\scratch.py", line 5, in  <module>
    x = raw_input(' %s W")? ' % (deg))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 1:
ordinal not in range(128)

我以为我可以按照指示添加编码 header 来解决问题 here (确实这确实使打印度数符号成为可能),但是当我向 raw_input 添加一个其他安全的字符串时,我仍然收到 Unicode 错误。这是怎么回事?

最佳答案

尝试将提示字符串编码为 stdout 的编码,然后再将其传递给原始输入

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys

deg = u'°'

prompt = u'40%s N, 100%s W)? ' % (deg, deg)
codelim = raw_input(prompt.encode(sys.stdout.encoding))

40° N, 100° W)?

关于python - 无法将度数符号输入 raw_input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28246004/

相关文章:

python - 从其他文件夹 python 导入模块(错误)

python - 如何使用 Numba 对具有多个输出的函数进行矢量化?

python - 为什么具有重新定义的 __getattr__() 的对象会抛出 TypeError?

java - Oracle 10g Clob 列中的特殊字符(UTF8 字符)返回为 ?或在 Java 中为空白

python - Unicode解码错误: 'ascii' codec can't decode byte 0xe2 in position 14: ordinal not in range(128) in GAE python?

python - 列表理解的扩展导致列表幂集中的无限循环

python - 在 qt 应用程序中显示 skimage 输出

python-2.7 - celery , flask sqlalchemy : DatabaseError: (DatabaseError) SSL error: decryption failed or bad record mac

python-2.7 - Popen.wait() 的常见/实际用途是什么

mysql - UTF-8字符有问题;我看到的不是我存储的