问题
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 stdout
s 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