如何将°(度)字符转换为字符串?
Answers:
将此行放在源代码的顶部
# -*- coding: utf-8 -*-
如果您的编辑器使用其他编码,请替换为utf-8
然后,您可以直接在源代码中包含utf-8字符
这是指定Unicode字符的对代码最友好的版本:
degree_sign= u'\N{DEGREE SIGN}'
注意:在\N构造中必须为大写N,以避免与'\ n'换行符混淆。大括号内的字符名称可以是任意大小写。
与字符的unicode索引相比,记住字符的名称要容易得多。它也更具可读性,易于调试。字符替换发生在编译时:.py[co]文件将包含用于的常量u'°':
>>> import dis
>>> c= compile('u"\N{DEGREE SIGN}"', '', 'eval')
>>> dis.dis(c)
1 0 LOAD_CONST 0 (u'\xb0')
3 RETURN_VALUE
>>> c.co_consts
(u'\xb0',)
>>> c= compile('u"\N{DEGREE SIGN}-\N{EMPTY SET}"', '', 'eval')
>>> c.co_consts
(u'\xb0-\u2205',)
>>> print c.co_consts[0]
°-∅
以上答案均假定可以安全地使用UTF8编码-该编码专门针对Windows。
Windows控制台通常使用CP850编码而不是utf-8,因此,如果您尝试使用utf8编码的源文件,则会得到这2个(不正确的)字符,┬░而不是度数°。
演示(在Windows控制台中使用python 2.7):
deg = u'\xb0` # utf code for degree
print deg.encode('utf8')
有效输出┬░。
修复:强制使用正确的编码(或更好地使用unicode):
local_encoding = 'cp850' # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg
或者,如果您使用显式定义编码的源文件:
# -*- coding: utf-8 -*-
local_encoding = 'cp850' # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)