split()、join()、replace()、strip()、find()等split():拆分字符串为列表# 默认按空白字符(空格、制表符、换行)拆分text = "Hello World Python"words = text.split()print(words) # ['Hello', 'World', 'Python']# 指定分隔符csv = "苹果,香蕉,橘子,葡萄"fruits = csv.split(",")print(fruits) # ['苹果', '香蕉', '橘子', '葡萄']# 限制拆分次数info = "小王,18,北京,编程"result = info.split(",", 2) # 最多拆2次print(result) # ['小王', '18', '北京,编程']join():把列表合并成字符串(split 的逆操作)# 用指定字符串连接列表元素words = ["Hello", "World", "Python"]sentence = " ".join(words)print(sentence) # Hello World Pythonfruits = ["苹果", "香蕉", "橘子"]result = "、".join(fruits)print(result) # 苹果、香蕉、橘子# 常见场景:把数字列表转成逗号分隔的字符串nums = [1, 2, 3, 4, 5]print(",".join(str(n) for n in nums)) # 1,2,3,4,5replace():替换子串text = "I love Java"new_text = text.replace("Java", "Python")print(new_text) # I love Pythonprint(text) # I love Java 原字符串不变!# 替换所有匹配项text = "aaa-bbb-aaa"print(text.replace("aaa", "ccc")) # ccc-bbb-ccc# 限制替换次数print(text.replace("aaa", "ccc", 1)) # ccc-bbb-aaastrip()/lstrip()/ rstrip():去除首尾空白字符# strip:去除两端空白text = " Hello World "print(text.strip()) # "Hello World"print(text.lstrip()) # "Hello World "print(text.rstrip()) # " Hello World"# 指定去除的字符text = "###Hello###"print(text.strip("#")) # Hello# 常见场景:清理用户输入name = input("请输入名字:").strip() # 去掉首尾多余空格find()/ rfind():查找子串位置text = "Hello World World"# find:从左找第一个出现的位置,返回索引print(text.find("World")) # 6print(text.find("Python")) # -1 找不到返回 -1,不报错# rfind:从右找最后一个出现的位置print(text.rfind("World")) # 12# 指定查找范围print(text.find("World", 7)) # 12 从索引7开始找startswith()/ endswith():判断首尾filename = "report.pdf"print(filename.endswith(".pdf")) # Trueprint(filename.endswith(".txt")) # Falseprint(filename.startswith("report")) # True# 常见场景:判断文件类型url = "https://example.com"print(url.startswith("https://")) # Trueupper()/lower()/ title():大小写转换text = "hello WORLD python"print(text.upper()) # HELLO WORLD PYTHONprint(text.lower()) # hello world pythonprint(text.title()) # Hello World Pythonprint(text.capitalize()) # Hello world python(只首字母大写)print(text.swapcase()) # HELLO world PYTHON(大小写互换)count():统计子串出现次数text = "banana"print(text.count("a")) # 3print(text.count("na")) # 2print(text.count("x")) # 0isdigit()/ isalpha()/ isalnum():类型判断print("123".isdigit()) # True 只含数字print("abc".isalpha()) # True 只含字母print("abc123".isalnum()) # True 只含字母或数字print("abc 123".isalnum()) # False 含空格# 常见场景:验证用户输入age = input("请输入年龄:")if age.isdigit(): print(f"你输入的年龄是 {int(age)}")else: print("请输入有效的数字!")split(sep) | ||
join(列表) | ||
replace(old, new) | ||
strip() | ||
find(sub) | ||
count(sub) | ||
upper()/ | ||
startswith(prefix) | ||
endswith(suffix) | ||
isdigit() | ||
isalpha() |
# 基本解包point = (3, 4)x, y = pointprint(x, y) # 3 4# 交换变量(不需要临时变量)a, b = 10, 20a, b = b, aprint(a, b) # 20 10# 扩展解包:用 * 收集多余元素t = (1, 2, 3, 4, 5)first, *middle, last = tprint(first) # 1print(middle) # [2, 3, 4] 变成列表print(last) # 5# 函数返回多个值时经常用元组defget_name_and_age():return"小王", 18# 返回的是元组name, age = get_name_and_age()print(name, age) # 小王 18tuple()和list()互相转换# 列表 → 元组lst = [1, 2, 3]t = tuple(lst)print(t) # (1, 2, 3)# 元组 → 列表t = (4, 5, 6)lst = list(t)print(lst) # [4, 5, 6]{}包裹,元素用逗号分隔(和字典区分:没有冒号):s = {1, 2, 3, 4, 5}print(type(s)) # <class 'set'># 空集合必须用 set(),不能用 {}empty = set() # ✅ 空集合not_a_set = {} # ❌ 这是空字典!print(type(empty)) # <class 'set'>print(type(not_a_set)) # <class 'dict'>| 无序 | [0] 访问 |
| 不重复 | |
| 可变 | |
| 元素必须不可变 |
# 自动去重s = {1, 2, 2, 3, 3, 3}print(s) # {1, 2, 3}# 无序:每次打印顺序可能不同s = {"苹果", "香蕉", "橘子"}print(s) # 顺序不确定# 不能用索引访问# s[0] # TypeError: 'set' object is not subscriptables = {1, 2, 3}# 添加元素s.add(4)print(s) # {1, 2, 3, 4}s.add(2) # 添加已有的元素,不会报错,但也不会重复print(s) # {1, 2, 3, 4}# 删除元素s.remove(3) # 删除元素,不存在会报错print(s) # {1, 2, 4}s.discard(99) # 删除元素,不存在不报错(更安全)# 随机删除一个元素s.pop() # 因为无序,所以是"随机"的# 清空s.clear()print(s) # set()a = {1, 2, 3, 4, 5}b = {4, 5, 6, 7, 8}# 交集:两个集合共有的元素print(a & b) # {4, 5}print(a.intersection(b)) # {4, 5}# 并集:两个集合的所有元素(去重)print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8}print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7, 8}# 差集:a有但b没有的print(a - b) # {1, 2, 3}print(a.difference(b)) # {1, 2, 3}# 对称差集:只在其中一个集合中出现的print(a ^ b) # {1, 2, 3, 6, 7, 8}print(a.symmetric_difference(b)) # {1, 2, 3, 6, 7, 8}a = {1, 2, 3, 4, 5}b = {2, 3}# b 是 a 的子集吗?print(b.issubset(a)) # Trueprint(b <= a) # True# a 是 b 的超集吗?print(a.issuperset(b)) # Trueprint(a >= b) # True# 两个集合是否没有交集c = {6, 7, 8}print(a.isdisjoint(c)) # True 没有公共元素# 场景一:列表去重nums = [1, 2, 2, 3, 3, 3, 4, 4, 5]unique = list(set(nums))print(unique) # [1, 2, 3, 4, 5] 顺序可能改变# 保持顺序的去重nums = [1, 2, 2, 3, 3, 3, 4, 4, 5]seen = set()unique_ordered = []for n in nums:if n notin seen: seen.add(n) unique_ordered.append(n)print(unique_ordered) # [1, 2, 3, 4, 5] 顺序保持# 场景二:判断元素是否在大量数据中(集合查找比列表快得多)valid_ids = {1001, 1002, 1003, 1004, 1005} # 用集合user_id = int(input("请输入ID:"))if user_id in valid_ids: print("有效ID")else: print("无效ID")# 场景三:找出两个列表的共同元素class_a = {"小王", "小李", "小张"}class_b = {"小张", "赵六", "小王"}both = class_a & class_bprint("两班都有的同学:", both) # {'小王', '小张'}[] | () | {} | {k:v} | |
# 选择指南# 需要增删改?→ 列表shopping_cart = ["苹果", "牛奶", "面包"]shopping_cart.append("鸡蛋")# 数据固定不变?→ 元组PI = (3, 14159265, 3589793)RGB_RED = (255, 0, 0)# 需要去重/求交集?→ 集合registered_emails = set()registered_emails.add("a@qq.com")# 需要通过名字查数据?→ 字典user = {"name": "小王", "age": 18}t1 = (42,) # 元组t2 = (42) # 不是元组!就是整数42print(type(t1)) # <class 'tuple'>print(type(t2)) # <class 'int'>{}s = {} # 这是字典!s = set() # ✅ 这才是空集合# s = {1, [2, 3]} # TypeError: unhashable type: 'list's = {1, (2, 3)} # ✅ 元组可以set()去重会打乱顺序names = ["小王", "小李", "小王", "小张", "小李"]unique = list(set(names))print(unique) # 顺序不确定!s = " hello "s.strip() # 返回新字符串,但 s 没变!print(s) # " hello " 还是原样s = s.strip() # ✅ 要重新赋值print(s) # "hello"find()找不到返回-1,index()找不到报错s = "hello"print(s.find("x")) # -1# print(s.index("x")) # ValueErrortext = input("请输入一段文字:").strip()words = text.split()print(f"字符数:{len(text)}")print(f"单词数:{len(words)}")target = input("请输入要查找的单词:")print(f"'{target}' 出现了 {text.count(target)} 次")alice_friends = ["小王", "小李", "小张", "赵六", "小王"]bob_friends = ["小张", "赵六", "钱七", "孙八"]alice_set = set(alice_friends)bob_set = set(bob_friends)common = alice_set & bob_setall_friends = alice_set | bob_setonly_alice = alice_set - bob_setprint(f"共同好友:{common}")print(f"所有好友:{all_friends}")print(f"只有Alice的好友:{only_alice}")# 模拟CSV数据data = "小王,92;小李,88;小张,95;赵六,48;钱七,73"records = data.split(";")result = []for record in records: name, score_str = record.split(",") score = int(score_str)if score >= 80: result.append(f"{name}({score}分)")print("优秀学生:", "、".join(result))# 优秀学生:小王(92分)、小李(88分)、小张(95分)split()、join()、replace()、strip()、find()等常用字符串方法find()(返回 -1)和 index()(报错)的不同x, y = point{}或set()创建&、并集|、差集-、对称差集^运算