Python
07 字典和字符串
按名字找数据、处理文本
- Python
- 入门
目标:学会「按名字查数据」的字典,和文本处理神器字符串方法。
1. 字典 dict:名片式的数据
列表靠序号取值,字典靠**键(key)**取值——像查字典一样,按词条找解释:
student = {
"name": "小明",
"age": 20,
"major": "计算机",
}
print(student["name"]) # 小明
print(student["age"]) # 20
字典最适合描述一个东西的多项属性:一个用户、一件商品、一条聊天记录。
2. 增删改查
student = {"name": "小明", "age": 20}
# 改 / 增:直接赋值(键存在就是改,不存在就是新增)
student["age"] = 21
student["city"] = "上海"
print(student) # {'name': '小明', 'age': 21, 'city': '上海'}
# 删
del student["city"]
# 查:[] 找不到会报 KeyError;get() 找不到返回 None(更安全)
print(student.get("name")) # 小明
print(student.get("phone")) # None
print(student.get("phone", "未填写")) # 未填写(给默认值)
3. 遍历字典
student = {"name": "小明", "age": 20, "major": "计算机"}
for key in student: # 默认遍历键
print(key, ":", student[key])
for key, value in student.items(): # 同时拿键和值(推荐)
print(f"{key} → {value}")
print(list(student.keys())) # 所有键 → ['name', 'age', 'major']
print(list(student.values())) # 所有值 → ['小明', 20, '计算机']
4. 列表套字典:真实程序的标准形态
一个班级 = 列表;一个学生 = 字典。这是日后做项目最常见的数据结构:
students = [
{"name": "小明", "score": 92},
{"name": "小红", "score": 85},
{"name": "小刚", "score": 58},
]
for s in students:
if s["score"] >= 60:
print(f"{s['name']} 及格:{s['score']}")
5. 字符串常用方法
字符串和列表、字典一样,是自带「技能」(方法)的,用 . 调用:
s = " Hello Python "
print(s.strip()) # "Hello Python" 去掉两端空白(处理输入必用)
print(s.lower()) # " hello python " 全转小写
print(s.upper()) # 全转大写
print(s.replace("Python", "World")) # 替换
print(s.strip().split(" ")) # ['Hello', 'Python'] 按分隔符切开 → 列表
print(len("你好")) # 2,中文一个字算一个字符
# join:把列表拼回字符串(split 的逆操作)
words = ["Hello", "Python"]
print("-".join(words)) # Hello-Python
# in 判断包含
print("Py" in "Python") # True
print("Python".startswith("Py")) # True(判断开头;endswith 判断结尾)
print("Python".find("th")) # 2(找子串位置;找不到返回 -1,不报错)
字符串是不可变的:所有方法都不会改动原字符串,而是返回新的:
s = "hello"
s.upper() # ❌ 这行白写,返回值没接住
s = s.upper() # ✅ 用新值覆盖旧值
print(s) # HELLO
字符串还能像列表一样按位置取值:s[0] 第一个字符、s[-1] 最后一个、s[1:4] 切片——规则和第 6 章的列表完全一样,得到的结果仍是字符串:
s = "Hello Python"
print(s[0]) # H
print(s[-1]) # n
print(s[0:5]) # Hello(切片,含头不含尾)
6. 字符串不能用 + 拼数字
age = 20
# print("我 " + age + " 岁") # ❌ TypeError
print("我 " + str(age) + " 岁") # ✅ 转字符串
print(f"我 {age} 岁") # ✅✅ 还是 f-string 最香
常见坑
- 字典的键是唯一的:
d = {"a": 1}再d["a"] = 2是覆盖,不是新增两条。 student["phone"]直接取不存在的键会崩;不确定就用.get()。input()收到的输入末尾虽没有换行,但常有多余空格——先strip()再用是个好习惯。
小练习
- 建一个自己的「个人名片」字典(姓名/年龄/爱好),遍历打印,再新增一项
city。 - 英文句子
"python is fun and python is powerful",统计python出现几次(提示:count()方法)。 - 统计上面句子里每个单词出现几次(提示:
split()切开,字典累加)。
练习答案
# 练习 1
card = {"姓名": "小明", "年龄": 20, "爱好": "打球"}
for k, v in card.items():
print(f"{k}:{v}")
card["city"] = "上海"
# 练习 2
sentence = "python is fun and python is powerful"
print(sentence.count("python")) # 2
# 练习 3
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
# {'python': 2, 'is': 2, 'fun': 1, 'and': 1, 'powerful': 1}