如何在python中的字符串中获取°字符?


Answers:


42

将此行放在源代码的顶部

# -*- coding: utf-8 -*-

如果您的编辑器使用其他编码,请替换为utf-8

然后,您可以直接在源代码中包含utf-8字符


假设您的编辑器使用UTF-8。如果您的编辑器使用其他字符集,请指出这一点。
伊格纳西奥·巴斯克斯

77

这是指定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]
°-∅

37
>>> u"\u00b0"
u'\xb0'
>>> print _
°

顺便说一句,我所做的就是在Google上搜索“ unicode学位”。这将产生两个结果:“度符号U + 00B0”和“度摄氏U + 2103”,它们实际上是不同的:

>>> u"\u2103"
u'\u2103'
>>> print _
℃

1
或者只是a = '\u00b0'在Python 3
JAB

@SilentGhost:是的,但是我不记得编号的小键盘代码,也不想当时查它。
JAB

1
谁记得数字键盘密码?:) 书写键序列是一个很多更容易记住; 学位只是Compose-oo。组合键是X Windows系统上的标准配置,但它也可用于Microsoft Windows。请参阅Wikipedia链接。
下午

13

您也可以使用chr(176)打印度数符号。这是使用python 3.6.5交互式shell的示例:

https://i.stack.imgur.com/spoWL.png


12

以上答案均假定可以安全地使用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)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.