Can't get a degree symbol into raw_input

百般思念 提交于 2019-12-23 19:22:49

问题


The problem in my code looks something like this:

#!/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))

I'm trying to generate a raw_input prompt for delimiter characters inside a latitude/longitude string, and the prompt should include an example of such a string. print deg and print '40%s N, 100%s W' % (deg, deg) both work fine -- they return "°" and "40° N, 100° W" respectively -- but the raw_input step fails every time. The error I get is as follows:

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)

I thought I'd have solved the problem by adding the encoding header, as instructed here (and indeed that did make it possible to print the degree sign at all), but I'm still getting Unicode errors as soon as I add an otherwise-safe string to raw_input. What's going on here?


回答1:


Try encoding the prompt string to stdouts encoding before passing it to raw input

#!/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)?



来源:https://stackoverflow.com/questions/28246004/cant-get-a-degree-symbol-into-raw-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!