NOTE目录骨架来自菜鸟教程 Python3 基础章节,表述与细节对照 Python 官方文档 与相关 PEP 核对。基于 Python 3。完整出处见文末 参考。
数字类型总览
Python 3 内置三种数值类型(Numeric Types):
| 类型 | 示例 | 说明 |
|---|---|---|
int | 0 42 -7 | 任意精度整数,仅受内存限制 |
float | 3.14 1e-3 | 双精度浮点(实现依赖平台,通常 IEEE 754) |
complex | 3+4j complex(2, -1) | 实部 + 虚部,虚部后缀 j |
type(1) # inttype(1.0) # floattype(2+3j) # complex(3+4j).real # 3.0(3+4j).imag # 4.0bool 是 int 子类(上一篇);算术里 True/False 当 1/0。精确小数用 decimal.Decimal、fractions.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,任意进制字符串 → intbin(10) # '0b1010'oct(10) # '0o12'hex(255) # '0xff'浮点可用科学计数:1.5e2 → 150.0。不要用 0.1 + 0.2 == 0.3 判断浮点相等;要精确小数用 decimal,或改成整数(比如按分来存)。
算术://、%、**
上一篇已列运算符;数字语境下再强调:
7 / 3 # 2.333...,真除恒为 float7 // 3 # 2,地板除-7 // 3 # -3(向负无穷,不是向零)7 % 3 # 1-7 % 3 # 2,与 // 配套2 ** 10 # 1024pow(2, 8) # 256,内置函数pow(2, 8, 5) # 1,模幂:2**8 % 5divmod(a, b) 返回 (a // b, a % b) 一对。复数不支持 // 和 %(以官方文档为准)。
混合类型:int 与 float 运算结果为 float;int 与 complex 得 complex。
math 模块(常用)
标准库 math 提供实数数学函数(多数要求 float,返回 float)。使用前 import math。
import mathmath.sqrt(2) # 1.414...math.pi # 常量math.emath.floor(3.7) # 3math.ceil(3.2) # 4math.fabs(-3) # 3.0math.log(100, 10) # 2.0,默认自然对数 math.log(x)math.sin(math.pi / 2) # 1.0math.hypot(3, 4) # 5.0,sqrt(x*x + y*y)math.inf、math.nan 与浮点特殊值行为见文档;比较 nan 用 math.isnan(x),不要用 ==。
random 模块(常用)
random 提供伪随机数(非密码学安全;安全场景用 secrets)。
import randomrandom.random() # [0.0, 1.0) 均匀 floatrandom.randint(1, 6) # 闭区间 [1, 6] 整数random.randrange(0, 10, 2) # 0,2,4,6,8random.choice(['a', 'b', 'c'])items = [1, 2, 3, 4]random.shuffle(items) # 原地打乱random.sample(range(100), 5) # 无重复抽样random.seed(42) # 可复现(调试);生产环境慎固定种子完整函数列表见附录;分布采样(gauss、uniform 等)用到时再查文档。
字符串:不可变文本序列
str 是 Unicode 码点序列(Text Sequence Type),不可变。引号成对即可:'、"、'''、""";内容相同时等价。
s = "Python"# s[0] = "p" # TypeErrors = "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',步长 2s[::-1] # 'nohtyP',反转切片总是产生新 str,不修改原串。越界单下标 IndexError;切片边界可宽松(超出当作端点)。
转义与 raw 字符串
反斜杠 \ 引入转义(String and Bytes literals):
| 转义 | 含义 |
|---|---|
\n | 换行 |
\t | 制表 |
\\ | 反斜杠 |
\' \" | 引号 |
\uXXXX | Unicode 码点(16 位) |
\UXXXXXXXX | Unicode 码点(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-string(PEP 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 = 30f"{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") # 1startswith / 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") # bytesb"\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) # bytesord("中") # 码点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, removesuffix | 3.9+ 去前后缀 |
split(sep=None, maxsplit=-1) | 拆分 |
rsplit, splitlines | 右拆 / 按行 |
startswith(prefix[, start[, end]]) | 前缀判断 |
partition(sep), rpartition(sep) | 三分 |
maketrans, translate | 字符映射 |
参考
官方文档(中文版 可对照阅读):
- Numeric Types — int, float, complex
- Text Sequence Type — str
- printf-style String Formatting
- An Informal Introduction to Python — Numbers, Strings
- Using Python as a Calculator — Strings
- Format String Syntax
- math — Mathematical functions
- random — Generate pseudo-random numbers
- Lexical analysis — Literals
PEP:
- PEP 498 — Literal String Interpolation (f-strings)
- PEP 515 — Underscores in Numeric Literals(如
1_000_000,可选)
目录来源(骨架,不以它为准改语法):