Python 字符串和常用数据结构

本文最后更新于 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() # 'HELLO, WORLD'
s.lower() # 'hello, world'
s.capitalize() # 'Hello, world'
s.title() # 'Hello, World'
s.strip() # 去掉两端空白,还有 lstrip/rstrip
s.replace('world', 'python') # 'hello, python'
s.split(',') # ['hello', ' world']
'-'.join(['a', 'b', 'c']) # 'a-b-c'

# 去掉指定的前后缀(3.9+),比切片直观
'https://iyuluo.com'.removeprefix('https://') # 'iyuluo.com'
'https://iyuluo.com'.removesuffix('.com') # 'https://iyuluo'

# 查找:find 找不到返回 -1,index 找不到会抛 ValueError
s.find('or') # 8
s.find('xyz') # -1

# 判断组成
'abc123'.isalnum() # True
'123'.isdigit() # True
'abc'.isalpha() # True
s.startswith('he') # True
s.endswith('ld') # True

切片

1
2
3
4
5
6
7
8
9
s = 'abcdef'

s[0] # 'a'
s[-1] # 'f'
s[1:4] # 'bcd'
s[:3] # 'abc'
s[3:] # 'def'
s[::2] # 'ace'
s[::-1] # 'fedcba',反转字符串的惯用写法

格式化

f-string 是现在的标准写法,3.12 起还支持嵌套同种引号和多行表达式:

1
2
3
4
5
name = 'yuluo'
age = 25
f'{name} is {age} years old' # 'yuluo is 25 years old'
f'{3.14159:.2f}' # '3.14'
f'{f"{name}".upper()}' # 'YULUO',f-string 里可以再套 f-string

3.14 新增的模板字符串(t-string,PEP 750)把插值留到渲染时再处理,适合需要转义或自定义渲染的场景:

1
template = t'{name} is {age}'   # 返回 Template 对象而非 str

旧的 % 和 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]

# 3.15 起推导式里可以直接解包(PEP 798),拍平嵌套序列很顺手
nested = [[1, 2], [3, 4]]
[*x for x in nested] # [1, 2, 3, 4]

元组 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'] # 'yuluo'
user.get('email', '无') # key 不存在时返回默认值,避免 KeyError
user['email'] = '[email protected]' # 新增或更新
del user['age'] # 删除

# 3.9 起可以用 | 合并,| 返回新字典,|= 原地更新
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'] # 1
fd['c'] = 3 # TypeError,不能修改
fd | {'c': 3} # frozendict({'a': 1, 'b': 2, 'c': 3}),返回新的 frozendict
hash(fd) # 可哈希

集合 set

无序、不重复的集合,主要用于去重和集合运算。

1
2
3
4
5
6
7
8
s1 = {1, 2, 3}
s2 = {2, 3, 4}

s1 & s2 # {2, 3},交集
s1 | s2 # {1, 2, 3, 4},并集
s1 - s2 # {1},差集

list(set([1, 2, 2, 3])) # 列表去重的惯用写法

怎么选

  • 要顺序、会修改 → list
  • 内容固定、不需要改 → tuple
  • 按键查值 → dict;要不可变、可哈希的映射 → frozendict
  • 去重、交并差运算 → set

Python 字符串和常用数据结构
https://iyuluo.com/2019/07/29/Python-字符串和常用数据结构/
作者
yuluo
发布于
2019年7月29日
许可协议