Python 基础 - 第八节


📋 本节要点

知识点 说明
字符串 用引号包裹的文本,不可变
索引访问 通过索引访问字符
字符串切片 截取字符串的一部分
拼接与重复 + 拼接,* 重复
join() 用指定字符拼接字符串列表
转义字符 \n 换行,\t 制表符
原始字符串 r"" 忽略转义
元组 用 () 表示,不可修改
元组与列表 列表可变 vs 元组不可变
字典 用 {} 表示,键值对结构
get() 安全获取字典中的值
keys()/values()/items() 获取键、值、键值对
集合 用 {} 表示,自动去重
集合运算 交集 &、并集 |、差集 -

1. 字符串(str)

字符串是用引号("" 或 '')包裹的文本,不可修改。一旦创建,不能改变其中的字符。

word = "hello,world"
print(word[5])    # ,(索引访问)
print(word[-1])   # d(负索引取最后一个)

# 不可变特性:以下代码会报错
# word[0] = "H"  # TypeError: 'str' object does not support item assignment

1.1 字符串切片

与列表一样,字符串支持切片操作:

text = "Hello, Python!"
print(text[0:5])     # Hello
print(text[7:])      # Python!
print(text[:5])      # Hello
print(text[::2])     # Hlo yhn(每隔一个字符)
print(text[::-1])    # !nohtyP ,olleH(反转字符串)

1.2 字符串拼接与重复

用 + 拼接字符串,用 * 重复字符串:

# 拼接 +
first = "Hello"
last = "World"
print(first + ", " + last + "!")  # Hello, World!

# 重复 *
print("Ha" * 3)   # HaHaHa
print("-" * 20)   # --------------------(分隔线)

运行结果:

Hello, World!
HaHaHa
--------------------

1.3 join() 拼接

join() 用指定字符将字符串列表连接成一个字符串:

words = ["Python", "is", "awesome"]
result = " ".join(words)
print(result)  # Python is awesome

result2 = "-".join(words)
print(result2)  # Python-is-awesome

运行结果:

Python is awesome
Python-is-awesome

1.4 转义字符

用反斜杠 \ 表示特殊字符:

print("第一行\n第二行")     # \n 换行
print("分类:\t水果\t蔬菜")  # \t 制表符对齐
print("她说:\"你好\"")      # \" 输出引号
print("反斜杠:\\")          # \\ 输出反斜杠本身

1.5 原始字符串 r''

在字符串前加 r,忽略所有转义字符,原样输出:

# 普通字符串:\n 会被解释为换行
print("第一行\n第二行")

# 原始字符串:\n 原样输出
print(r"第一行\n第二行")  # 第一行\n第二行

# 常用场景:Windows 文件路径
path = r"C:\Users\new_folder\test.py"
print(path)  # C:\Users\new_folder\test.py

运行结果:

第一行\n第二行
C:\Users\new_folder\test.py

2. 元组(tuple)

元组用 () 表示,与列表类似,但不可修改(不可变)。

subjects = ("英语", "数学", "语文")
print(subjects[1])   # 数学(索引访问)
print(subjects[:2])  # ('英语', '数学')(切片)

# 不可变:以下代码会报错
# subjects[0] = "物理"  # TypeError

元组与列表的区别

比较 列表 list 元组 tuple
语法 [] ()
可变性 可增删改 不可修改
速度 较慢 较快
用途 需要频繁修改的数据 固定不变的数据
# 列表可变
list_data = [1, 2, 3]
list_data[1] = 99  # 可以修改
print(list_data)   # [1, 99, 3]

# 元组不可变
tuple_data = (1, 2, 3)
# tuple_data[1] = 99  # TypeError

# 元组适合存储固定数据(如坐标、日期等)
point = (100, 200)
color_rgb = (255, 0, 0)

3. 字典(dict)

字典用 {} 表示,存储的是键值对(key-value),通过键来访问值。

info = {"name": "tom", "age": 17, "gender": "male"}

# 获取值:[] vs get()
print(info["name"])           # tom
print(info.get("age"))        # 17
print(info.get("score"))      # None(不存在不报错)
print(info.get("score", 0))   # 0(不存在返回默认值)

3.1 字典添加与修改

# 添加新键值对
info["score"] = 95
print(info)  # {'name': 'tom', 'age': 17, 'gender': 'male', 'score': 95}

# 修改已有键的值
info["age"] = 18
print(info)  # {'name': 'tom', 'age': 18, ...}

3.2 字典删除 pop() / del

# pop() 删除并返回值
gender = info.pop("gender")
print(gender)  # male
print(info)    # {'name': 'tom', 'age': 18, 'score': 95}

# del 删除指定键
del info["score"]
print(info)  # {'name': 'tom', 'age': 18}

3.3 遍历字典 keys() / values() / items()

info = {"name": "tom", "age": 17, "gender": "male"}

# keys() 获取所有键
print(info.keys())    # dict_keys(['name', 'age', 'gender'])
for key in info.keys():
    print(key)

# values() 获取所有值
print(info.values())  # dict_values(['tom', 17, 'male'])
for value in info.values():
    print(value)

# items() 获取所有键值对
for key, value in info.items():
    print(f"{key} → {value}")

运行结果:

name → tom
age → 17
gender → male

4. 集合(set)

集合用 {} 表示,存储不重复的元素,会自动去除重复值。注意空集合要用 set() 创建。

# 创建集合
numbers = {1, 2, 3, 3, 2, 1}
print(numbers)              # {1, 2, 3}(自动去重)
print(type(numbers))        # <class 'set'>

# 空集合
empty_set = set()            # 空集合
empty_dict = {}              # 这是空字典,不是空集合!
print(type(empty_set))       # <class 'set'>
print(type(empty_dict))      # <class 'dict'>

4.1 添加元素 add()

fruits = {"苹果", "香蕉"}
fruits.add("橘子")
print(fruits)  # {'橘子', '苹果', '香蕉'}

fruits.add("苹果")  # 重复添加不会报错,但不会增加
print(fruits)      # {'橘子', '苹果', '香蕉'}(不变)

4.2 删除元素 remove() / discard()

fruits = {"苹果", "香蕉", "橘子"}

# remove() 删除指定元素(不存在会报错)
fruits.remove("香蕉")
print(fruits)  # {'橘子', '苹果'}

# discard() 删除指定元素(不存在不会报错)
fruits.discard("西瓜")  # 无此元素,但不会报错
fruits.discard("苹果")
print(fruits)  # {'橘子'}

4.3 集合运算

集合支持数学中的集合运算:

a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

# 交集 &:两个集合都有的元素
print(a & b)     # {4, 5}

# 并集 |:合并两个集合的所有元素(去重)
print(a | b)     # {1, 2, 3, 4, 5, 6, 7, 8}

# 差集 -:在 a 中但不在 b 中的元素
print(a - b)     # {1, 2, 3}
print(b - a)     # {8, 6, 7}

集合的特点:① 自动去重 ② 元素无序 ③ 支持数学集合运算。常用于去重和成员关系判断。


下一节预告:函数基础