[英]How to get a part of a string using a start character and a end character in python
[英]How to get ° character in a string in python?
如何将°
(度)字符放入字符串中?
这是指定 Unicode 字符的对编码人员最友好的版本:
degree_sign = u'\N{DEGREE SIGN}'
转义序列: \\N{name}
含义: Unicode 数据库中名为name的字符
参考: https : //docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
笔记:
"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]
°-∅
>>> u"\u00b0"
u'\xb0'
>>> print _
°
顺便说一句,我所做的只是在谷歌上搜索“unicode degree”。 这带来了两个结果:“Degree sign U+00B0”和“DegreeCelsius U+2103”,实际上是不同的:
>>> u"\u2103"
u'\u2103'
>>> print _
℃
将此行放在源的顶部
# -*- coding: utf-8 -*-
如果您的编辑器使用不同的编码,请替换为 utf-8
然后就可以直接在源码中包含utf-8字符了
上面的答案假设可以安全地使用 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)
只需使用\\xb0 (in a string);
python会自动转换
使用 python f-string
, f"{var}"
,您可以使用:
theta = 45
print(f"Theta {theta}\N{DEGREE SIGN}.")
输出: Theta 45°.
*改进tzot答案
特殊情况:将字符串发送到 16x2 或 20x4 LCD(例如连接到带有 I2C LCD 显示器的 Raspberry Pi):
f"Outside Temp: {my_temp_variable}{chr(223)}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.