本文最后更新于 2026年11月16日 上午
记录一下 Python 字符串的常用操作和几种内置数据结构的用法,基于 Python 3.15。
字符串 字符串是不可变类型,所有”修改”操作返回的都是新字符串,原字符串不变。3.15 起 UTF-8 已成为默认编码(PEP 686),处理文本时不用再惦记系统默认编码的差异。
常用方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 s = 'hello, world' s.upper() s.lower() s.capitalize() s.title() s.strip() s.replace('world' , 'python' ) s.split(',' ) '-' .join(['a' , 'b' , 'c' ]) 'https://iyuluo.com' .removeprefix('https://' ) 'https://iyuluo.com' .removesuffix('.com' ) s.find('or' ) s.find('xyz' ) 'abc123' .isalnum() '123' .isdigit() 'abc' .isalpha() s.startswith('he' ) s.endswith('ld' )
切片 1 2 3 4 5 6 7 8 9 s = 'abcdef' s[0 ] s[-1 ] s[1 :4 ] s[:3 ] s[3 :] s[::2 ] s[::-1 ]
格式化 f-string 是现在的标准写法,3.12 起还支持嵌套同种引号和多行表达式:
1 2 3 4 5 name = 'yuluo' age = 25 f'{name} is {age} years old' f'{3.14159 :.2 f} ' f'{f"{name} " .upper()} '
3.14 新增的模板字符串(t-string,PEP 750)把插值留到渲染时再处理,适合需要转义或自定义渲染的场景:
1 template = t'{name} is {age}'
旧的 % 和 format() 写法依然可用:
1 2 '%s is %d' % (name, age)'{} is {}' .format (name, age)
列表 list 有序、可变的序列,最常用的容器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 fruits = ['apple' , 'banana' , 'orange' ] fruits.append('grape' ) fruits.insert(0 , 'pear' ) fruits.remove('banana' ) fruits.pop() fruits.sort() sorted (fruits) [x * x for x in range (10 ) if x % 2 == 0 ] nested = [[1 , 2 ], [3 , 4 ]] [*x for x in nested]
元组 tuple 不可变序列,适合表示固定结构的数据(坐标、配置项),也可以作字典的 key。
1 2 point = (3 , 4 ) x, y = point
只有一个元素时要加逗号:t = (1,),否则 t 是 int 而不是元组。
字典 dict 键值对集合,key 必须是不可变类型。3.7 起字典保证按插入顺序遍历,这已是语言规范而不是实现细节。
1 2 3 4 5 6 7 8 9 10 11 12 user = {'name' : 'yuluo' , 'age' : 25 } user['name' ] user.get('email' , '无' ) user['email' ] = '[email protected] ' del user['age' ] user | {'city' : 'nanjing' }for k, v in user.items(): print (k, v)
frozendict 3.15 新增了内置的不可变字典 frozendict(PEP 814)。它是可哈希的,可以作字典的 key 或放进 set,也适合用来表示不想被修改的映射:
1 2 3 4 5 6 fd = frozendict({'a' : 1 , 'b' : 2 }) fd['a' ] fd['c' ] = 3 fd | {'c' : 3 } hash (fd)
集合 set 无序、不重复的集合,主要用于去重和集合运算。
1 2 3 4 5 6 7 8 s1 = {1 , 2 , 3 } s2 = {2 , 3 , 4 } s1 & s2 s1 | s2 s1 - s2 list (set ([1 , 2 , 2 , 3 ]))
怎么选
要顺序、会修改 → list
内容固定、不需要改 → tuple
按键查值 → dict;要不可变、可哈希的映射 → frozendict
去重、交并差运算 → set