2.1 基础知识
2.1.1 数值基础
分类:整形(int) 浮点型(float) 复数类型(complex eg: 1+2j
)
长数字:加_
使其更易读(eg: i = 1_000_000_000
)
浮点数精度问题
>>> 0.1 + 0.2
0.30000000000000004
>>> 1.1 + 0.2
1.3
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.2')
Decimal('0.3')
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
注意: Decimal
只能使用字符串作为输入
2.1.2 布尔值也是数字
>>>True + 1
2
求列表中偶数的个数
count = sum(i % 2 == 0 for i in numbers)
2.1.3 字符串常用操作
把字符串当做序列
遍历
切片
翻转:
s[::-1]
or
.join(reversed(s))
>>> s = "hello"
>>> reversed(s)
<reversed object at 0x7fbe7efc6e90>
>>> list(reversed(s))
['o', 'l', 'l', 'e', 'h']
>>> ''.join(reversed(s))
'olleh'
字符串格式化
分类:%
.format
f-string
format 特殊之处:通过位置参数实现参数复用
'{0}: name={0} score={1}'.format(name, score)
拼接多个字符串(参考2.3.5)
- 把需要拼接的字符串都放在列表中,然后
join
+=
2.1.4 冷门神器字符串方法
partition
>>> "a:b".partition(":")
('a', ':', 'b')
>>> "a:".partition(":")
('a', ':', '')
>>> "a".partition(":")
('a', '', '')
>>> "".partition(":")
('', '', '')
translate
按照规则一次性替换多个字符
>>> s = "中文, 但是用的是英文标点."
>>> table = s.maketrans(',.', ',。')
>>> s.translate(table)
'中文, 但是用的是英文标点。'
2.1.5 字符串与字节串
字符串 str Unicode 通过.encode() 编码为字节串
字节串 bytes UTF-8(default) 通过.decode()解码为字符串
>>> s = "Hello, 世界!"
>>> s.encode()
b'Hello, \xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
>>>
>>> b = b'Hello'
>>> b.decode()
'Hello'
2.2 案例故事
2.2.1
Enum
TODO:会另开一贴讲述什么时候使用Enum以及如何使用
2.2.2
参数化查询防止sql注入
TODO:此处留白,会搞懂后另开一贴
jinja2 Template 拼接非结构化字符串
TODO:另开一贴放链接
2.3 编程建议
2.3.1 不必预计算字面量表达式
dis 模块
TODO:另开一贴放链接
2.3.2 使用无穷大
float("inf") & float("-inf")
2.3.3 g改善超长字符串的可读性
除了使用\
+
, 还可以用()
将字符串包起来
多级缩进多行字符串(不包含缩进里的空格):
from textwrap import dedent
def main():
if 1 > 0:
message = dedent("""\
My List:
- A
- B
- C""")
print(message)
main()
output:
My List:
- A
- B
- C
2.3.4 r开头字符串内置方法
>>> s = "Hello, string world!"
>>> s.split(" ", maxsplit=1)
['Hello,', 'string world!']
>>>
>>> s.rsplit(" ", maxsplit=1)
['Hello, string', 'world!']
2.3.5 不要害怕字符串拼接
+=
和 join
性能差不多