1761 字
9 分钟
Python 札记 (3)
2026-08-26
NOTE

目录骨架来自菜鸟教程 Python3 基础章节,表述与细节对照 Python 官方文档 与相关 PEP 核对。基于 Python 3。完整出处见文末 参考

数字类型总览#

Python 3 内置三种数值类型(Numeric Types):

类型示例说明
int0 42 -7任意精度整数,仅受内存限制
float3.14 1e-3双精度浮点(实现依赖平台,通常 IEEE 754)
complex3+4j complex(2, -1)实部 + 虚部,虚部后缀 j
type(1) # int
type(1.0) # float
type(2+3j) # complex
(3+4j).real # 3.0
(3+4j).imag # 4.0

boolint 子类(上一篇);算术里 True/False 当 1/0。精确小数用 decimal.Decimalfractions.Fraction,这里不展开。

字面量与进制#

int 字面量可带进制前缀(Integer literals);数字里可用下划线分组(PEP 515):1_000_000

前缀含义示例
0b / 0B二进制0b1010 → 10
0o / 0O八进制0o12 → 10
0x / 0X十六进制0xFF → 255
int("1010", 2) # 10,任意进制字符串 → int
bin(10) # '0b1010'
oct(10) # '0o12'
hex(255) # '0xff'

浮点可用科学计数:1.5e2150.0不要用 0.1 + 0.2 == 0.3 判断浮点相等;要精确小数用 decimal,或改成整数(比如按分来存)。

算术://、%、**#

上一篇已列运算符;数字语境下再强调:

7 / 3 # 2.333...,真除恒为 float
7 // 3 # 2,地板除
-7 // 3 # -3(向负无穷,不是向零)
7 % 3 # 1
-7 % 3 # 2,与 // 配套
2 ** 10 # 1024
pow(2, 8) # 256,内置函数
pow(2, 8, 5) # 1,模幂:2**8 % 5

divmod(a, b) 返回 (a // b, a % b) 一对。复数不支持 //%(以官方文档为准)。

混合类型:intfloat 运算结果为 floatintcomplexcomplex

math 模块(常用)#

标准库 math 提供实数数学函数(多数要求 float,返回 float)。使用前 import math

import math
math.sqrt(2) # 1.414...
math.pi # 常量
math.e
math.floor(3.7) # 3
math.ceil(3.2) # 4
math.fabs(-3) # 3.0
math.log(100, 10) # 2.0,默认自然对数 math.log(x)
math.sin(math.pi / 2) # 1.0
math.hypot(3, 4) # 5.0,sqrt(x*x + y*y)

math.infmath.nan 与浮点特殊值行为见文档;比较 nanmath.isnan(x),不要用 ==

random 模块(常用)#

random 提供伪随机数(非密码学安全;安全场景用 secrets)。

import random
random.random() # [0.0, 1.0) 均匀 float
random.randint(1, 6) # 闭区间 [1, 6] 整数
random.randrange(0, 10, 2) # 0,2,4,6,8
random.choice(['a', 'b', 'c'])
items = [1, 2, 3, 4]
random.shuffle(items) # 原地打乱
random.sample(range(100), 5) # 无重复抽样
random.seed(42) # 可复现(调试);生产环境慎固定种子

完整函数列表见附录;分布采样(gaussuniform 等)用到时再查文档。

字符串:不可变文本序列#

str 是 Unicode 码点序列(Text Sequence Type),不可变。引号成对即可:'"'''""";内容相同时等价。

s = "Python"
# s[0] = "p" # TypeError
s = "python" # 新对象

len(s) 是字符个数(对多数日常文本即码点数;精确 Unicode 语义见 Unicode HOWTO)。

索引与切片#

下标从 0 起;负下标从末尾计:-1 是最后一个。

s = "Python"
s[0] # 'P'
s[-1] # 'n'
s[1:4] # 'yth',左闭右开
s[:3] # 'Pyt'
s[3:] # 'hon'
s[::2] # 'Pto',步长 2
s[::-1] # 'nohtyP',反转

切片总是产生新 str,不修改原串。越界单下标 IndexError;切片边界可宽松(超出当作端点)。

转义与 raw 字符串#

反斜杠 \ 引入转义(String and Bytes literals):

转义含义
\n换行
\t制表
\\反斜杠
\' \"引号
\uXXXXUnicode 码点(16 位)
\UXXXXXXXXUnicode 码点(32 位)
print("line1\nline2")
print(r"C:\new\test") # raw:不处理转义,\\ 仍保留
# r"C:\new" 末尾 \ 可能引发语法问题,注意结尾反斜杠

路径、正则模式常用 r"...";具体规则以词法文档为准。

拼接与重复#

"Hello, " + "World" # 连接
"*" * 30 # 重复 30 次
# "a" + 1 # TypeError,需 str(1)

"".join(iterable) 往往比循环 + 高效(大列表拼串时),见后文 join

格式化:%、str.format、f-string#

三种主流写法并存;新代码优先 f-stringPEP 498,3.6+)。

% 格式化(旧式)#

"%.2f %s" % (3.14159, "pi") # '3.14 pi'
"%d" % 42
"%(name)s" % {"name": "Alice"}

映射与 % 运算符见 printf-style String Formatting;维护旧代码时查表即可。

str.format#

"{} + {} = {}".format(1, 2, 3)
"{1} {0}".format("world", "hello")
"{name}: {age}".format(name="Bob", age=20)
"{:.2f}".format(3.14159)
"{:>10}".format("右对齐")

格式规格 mini-language 见 Format String Syntax;记不住就查官方表。

f-string(推荐)#

name = "Alice"
age = 30
f"{name} is {age} years old"
f"{3.14159:.2f}"
f"{2 + 3}"
f"{name!r}" # 等价于 repr(name)
f"{name.lower()=}" # 3.8+ 调试

f-string 花括号内可以是表达式;不能嵌套同一引号未转义的花括号。3.12+ 的 f-string 细节变更以当前版本 What’s New 为准。

常用 str 方法#

完整方法表见附录;日常高频:

split 与 join#

"a,b,c".split(",") # ['a', 'b', 'c']
"a b c".split() # 默认按任意空白切
",".join(['a', 'b', 'c']) # 'a,b,c'

strip 系列#

" hello ".strip() # 'hello'
"xxxhelloxxx".strip("x") # 'hello'
" hi".lstrip()
"hi ".rstrip()

replace#

"hello".replace("l", "L") # 'heLLo'
"hello".replace("l", "L", 1) # 只换 1 次

find / index#

"python".find("th") # 2,找不到 -1
"python".index("th") # 2,找不到 ValueError
"python".count("o") # 1

startswith / endswith#

"hello.py".startswith("hello")
"hello.py".endswith(".py")
"hello.py".removesuffix(".py") # 3.9+,'hello'

大小写与判断#

"Hello".lower()
"Hello".upper()
"hello world".title()
"123".isdigit()
"abc".isalpha()
" ".isspace()

encode#

"中文".encode("utf-8") # bytes
b"\xe4\xb8\xad".decode("utf-8")

编码错误策略(errors=)与 codecs 见官方文档。

字符串与 bytes#

str 是文本,bytes 是字节序列(0–255)。网络、文件二进制读写要在二者间显式编解码,Python 3 不会自动混用。b"..." 字面量只能写 ASCII 或转义;bytes 下标得到的是 int。需要原地改用 bytearray

text = "你好"
data = text.encode("utf-8")
text2 = data.decode("utf-8")
type(data) # bytes
ord("中") # 码点
chr(20013) # '中'

附录:math 模块函数表(选)#

math — Mathematical functions 为准;下表便于速查:

函数 / 常量说明
pi, e, tau, inf, nan常数
ceil(x), floor(x), trunc(x)取整方向不同
fabs(x)绝对值(float)
factorial(n)n!
gcd(a, b), lcm(a, b)最大公约数 / 最小公倍数(3.9+ lcm)
sqrt(x), pow(x, y)平方根 / x^y
exp(x), log(x[, base]), log10(x), log2(x)指数与对数
sin, cos, tan, asin, acos, atan, atan2三角
degrees(x), radians(x)弧度 ↔ 角度
hypot(x, y)sqrt(x²+y²)
isfinite(x), isinf(x), isnan(x)浮点检测
copysign(x, y), fmod(x, y), remainder(x, y)符号与余数

附录:random 模块函数表(选)#

random — Generate pseudo-random numbers 为准:

函数说明
seed(a=None, version=2)初始化生成器
random()[0.0, 1.0) float
uniform(a, b)[a, b] 均匀 float
randint(a, b)[a, b] 整数
randrange(start, stop[, step])半开区间整数
choice(seq)随机元素
choices(population, weights=None, k=1)可重复抽样
sample(population, k)无重复抽样
shuffle(x)原地洗牌
getrandbits(k)k 位随机整数
gauss(mu, sigma), normalvariate, expovariate分布(按需查文档)

附录:str 常用方法表#

Text Sequence Type — str 为准;完整列表以官方为准

方法说明
capitalize()首字母大写
casefold()强大小写折叠(比较用)
center(width[, fillchar])居中填充
count(sub[, start[, end]])子串出现次数
encode(encoding='utf-8', errors='strict')→ bytes
endswith(suffix[, start[, end]])后缀判断
expandtabs(tabsize=8)tab → 空格
find(sub[, start[, end]])查找,失败 -1
format(*args, **kwargs)格式化
format_map(mapping)映射格式化
index(sub[, start[, end]])查找,失败 ValueError
isalnum(), isalpha(), isdigit(), isspace()字符类判断
join(iterable)连接
ljust, rjust, zfill对齐与填零
lower(), upper(), swapcase(), title()大小写
lstrip, rstrip, strip([chars])去空白或字符集
replace(old, new[, count])替换
removeprefix, removesuffix3.9+ 去前后缀
split(sep=None, maxsplit=-1)拆分
rsplit, splitlines右拆 / 按行
startswith(prefix[, start[, end]])前缀判断
partition(sep), rpartition(sep)三分
maketrans, translate字符映射

参考#

官方文档(中文版 可对照阅读):

  1. Numeric Types — int, float, complex
  2. Text Sequence Type — str
  3. printf-style String Formatting
  4. An Informal Introduction to Python — Numbers, Strings
  5. Using Python as a Calculator — Strings
  6. Format String Syntax
  7. math — Mathematical functions
  8. random — Generate pseudo-random numbers
  9. Lexical analysis — Literals

PEP:

  1. PEP 498 — Literal String Interpolation (f-strings)
  2. PEP 515 — Underscores in Numeric Literals(如 1_000_000,可选)

目录来源(骨架,不以它为准改语法):

  1. 菜鸟教程 · Number
  2. 菜鸟教程 · 字符串
  3. 菜鸟教程 · 格式化
Python 札记 (3)
https://blog.chuwu.top/posts/python/python3/
作者
ChuwuYo
发布于
2026-08-26
许可协议
CC BY-NC-SA 4.0