tzo*_*zot 63
这是指定unicode字符的最符合编码器的版本:
degree_sign= u'\N{DEGREE SIGN}'
Run Code Online (Sandbox Code Playgroud)
注意:必须是\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]
°-?
Run Code Online (Sandbox Code Playgroud)
Joh*_*ooy 37
将此行放在源代码的顶部
# -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)
如果您的编辑器使用不同的编码,请替换utf-8
然后,您可以直接在源中包含utf-8字符
ada*_*amk 30
>>> u"\u00b0"
u'\xb0'
>>> print _
°
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我所做的就是在Google上搜索"unicode degree".这会产生两个结果:"度符号U + 00B0"和"度摄氏度U + 2103",它们实际上是不同的:
>>> u"\u2103"
u'\u2103'
>>> print _
?
Run Code Online (Sandbox Code Playgroud)
以上答案假设可以安全地使用UTF8编码 - 这个编码专门针对Windows.
Windows控制台通常使用CP850编码而不使用 utf-8,因此如果您尝试使用utf8编码的源文件,则会获得这两个(不正确的)字符??
而不是度°
.
演示(在Windows控制台中使用python 2.7):
deg = u'\xb0` # utf code for degree
print deg.encode('utf8')
Run Code Online (Sandbox Code Playgroud)
有效输出??
.
修复:只需强制正确编码(或更好地使用unicode):
local_encoding = 'cp850' # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg
Run Code Online (Sandbox Code Playgroud)
或者如果您使用明确定义编码的源文件:
# -*- 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)
Run Code Online (Sandbox Code Playgroud)
使用 python f-string
,f"{var}"
您可以使用:
theta = 45\nprint(f"Theta {theta}\\N{DEGREE SIGN}.")\n
Run Code Online (Sandbox Code Playgroud)\n输出:Theta 45\xc2\xb0.
*改进tzot 答案
\n 归档时间: |
|
查看次数: |
104003 次 |
最近记录: |