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

Ric*_*ard 58 python string

如何将°(度)字符转换为字符串?

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)

  • @JAB:或者只是'a ='°'`. (8认同)
  • 或者在 Python 3 中只是 `a = '\u00b0'`。 (3认同)

Ser*_*sta 9

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


小智 7

只需使用\xb0 (in a string);python就会自动转换它


小智 7

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

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


Muh*_*oni 7

使用 python f-stringf"{var}"您可以使用:

\n
theta = 45\nprint(f"Theta {theta}\\N{DEGREE SIGN}.")\n
Run Code Online (Sandbox Code Playgroud)\n

输出:Theta 45\xc2\xb0.

\n

*改进tzot 答案

\n