我如何将°
(度)符号添加到字符串中?
这是最适合程序员的指定 Unicode 字符的版本:
degree_sign = u'\N{DEGREE SIGN}'
转义序列:\N{name}
含义:Unicode数据库中名为name的字符
参考:https://docs.python.org/zh-cn/3/reference/lexical_analysis.html#string-and-bytes-literals
注意:
在\N
结构中,N
必须大写,以避免与换行符\n
混淆
花括号内的字符名称可以是任何大小写形式
记住字符的名称比它的Unicode索引更容易。这也更可读,因此更易于调试。字符替换发生在编译时,即.py[co]
文件将包含一个常量'°':
>>> 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]
°-∅
>>> u"\u00b0"
u'\xb0'
>>> print _
°
顺便说一下,我只是在Google上搜索了“unicode degree”。这会得到两个结果:“度符号U+00B0”和“摄氏度U+2103”,它们实际上是不同的:
>>> u"\u2103"
u'\u2103'
>>> print _
℃
a = '\u00b0'
即可。 - JAB把这行代码放在你的源文件顶部
# -*- coding: utf-8 -*-
如果您的编辑器使用不同的编码,请将其替换为 utf-8。只需在字符串中使用\xb0
,Python会自动转换
上述答案假设可以安全使用UTF8编码-但这个答案特别针对Windows。
Windows控制台通常使用CP850编码,而不是utf-8,因此如果您尝试使用utf8编码的源文件,则会得到这两个(不正确的)字符┬░
,而不是度数符号°
。
演示(在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)
利用Python中的f-string
,f"{var}"
,你可以使用:
theta = 45
print(f"Theta {theta}\N{DEGREE SIGN}.")
输出:Theta 45°。
*改进tzot的回答
特殊情况:向16x2或20x4 LCD发送字符串(例如,连接到带有I2C LCD显示器的树莓派):
f"Outside Temp: {my_temp_variable}{chr(223)}"