我的代码中的问题看起来像这样:
#!/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 deg
和 print '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/