如何获得°;python中字符串中的字符?
如何将如何获得°;python中字符串中的字符?,python,string,Python,String,如何将°(度)字符转换为字符串 >>> u"\u00b0" u'\xb0' >>> print _ ° 顺便说一句,我所做的只是在谷歌上搜索“unicode学位”。这带来了两个结果: “度符号U+00B0”和“摄氏度U+2103”实际上是不同的: >>> u"\u2103" u'\u2103' >>> print _ ℃ 将这一行放在源代码的顶部 # -*- coding: utf-8 -*- 如果编辑器使用不同的编码
°
(度)字符转换为字符串
>>> u"\u00b0"
u'\xb0'
>>> print _
°
顺便说一句,我所做的只是在谷歌上搜索“unicode学位”。这带来了两个结果:
“度符号U+00B0”和“摄氏度U+2103”实际上是不同的:
>>> u"\u2103"
u'\u2103'
>>> print _
℃
将这一行放在源代码的顶部
# -*- 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]
°-∅
只需使用
\xb0(字符串形式)代码>python将自动转换它以上答案假设可以安全地使用UTF8编码-此编码专门针对Windows
Windows控制台通常使用CP850编码,而不是utf-8,因此如果尝试使用utf8编码的源文件,则会得到这2个(不正确的)字符┬░代码>而不是学位°
演示(在windows控制台中使用python 2.7):
有效输出<代码>┬░代码>
修正:只需强制使用正确的编码(或者更好地使用unicode):
或者,如果使用明确定义编码的源文件:
# -*- 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)
您还可以使用chr(176)
打印学位标志。
下面是一个使用python 3.6.5交互式shell的示例:
使用pythonf-string
,f“{var}”
,您可以使用:
theta=45
打印(f“Theta{Theta}\N{DEGREE SIGN}.”)
输出:Theta 45°。
*在Python 3中改进或只是a='\u00b0'
。@SilentGhost:是的,但我不记得°的numpad代码,当时也不想查找它。谁记得numpad代码?:)序列更容易记忆;学位就是组成。Compose键是X windows系统上的标准键,但也可用于Microsoft windows;请参阅Wikipedia链接。假设您的编辑器使用UTF-8。如果您的编辑器使用不同的字符集,请指出该字符集。请查看您是否试图在Windows系统上打印学位标志。
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)