Python 工匠 第二章 数值与字符串

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)

  1. 把需要拼接的字符串都放在列表中,然后join
  2. +=

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 性能差不多

2.4 总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值