作者:着迷不白字符串和列表是 Python 中最常用的两种序列类型。字符串是不可变的字符序列,列表是可变的任意元素序列。本篇带你掌握字符串的下标、切片、常用方法,以及列表的增删改查操作。作业 + 答案在文末,方便自测。
在前两篇笔记中,我们学习了变量、数据类型、输入输出以及类型转换。从本篇开始,我们将正式接触 Python 中最重要的两种数据结构——字符串和列表。
"hello",一旦创建就不能修改(不可变)。[1, 2, "a"],并且可以随时增删改(可变)。掌握它们,你就能处理大多数文本数据和集合数据了。
字符串可以使用单引号、双引号或三引号创建。三引号常用于多行字符串。
# 单引号s1 = 'Hello'# 双引号s2 = "world"# 三引号(可换行)s3 = """这是多行字符串"""# 拼接s4 = s1 + ", " + s2 + "!"print(s4) # Hello, world!每个字符在字符串中都有一个下标(索引),从 0 开始。可以用 [下标] 获取对应字符。
my_string = "Hello, world!"print(my_string[0]) # H(第一个字符)print(my_string[4]) # o(第五个字符)print(my_string[7]) # w(第八个字符)⚠️ 下标不能超出范围,否则报错
IndexError。
my_string = "Hello, world!"print(my_string[-1]) # !(最后一个字符)print(my_string[-2]) # d(倒数第二个字符)print(my_string[-8]) # ,(逗号)str1 = "python"print(str1[1]) # y(第2个字符)print(str1[4]) # o(第5个字符)切片用于获取字符串中的一段子串,语法:[start:stop:step]
start:起始下标(包含),省略则从开头开始stop:结束下标(不包含),省略则到末尾结束step:步长,默认 1,可为负数(反向)s = "Hello, world!"print(s[0:5]) # Hello(下标0~4)print(s[7:]) # world!(下标7到末尾)print(s[:5]) # Hello(省略start,默认0)print(s[::]) # Hello, world!(完整字符串)s = "Hello, world!"print(s[::2]) # Hlo ol!(每隔一个取一个)s = "Hello"print(s[::-1]) # olleHstr2 = "Python"print(str2[2:4]) # th(下标2~3)print(str2[1::3]) # yo(从下标1开始,步长3)len(s) | len("hello") | |
s.find(sub) | "hello".find("ll") | |
s.index(sub) | "hello".index("ll") | |
s.replace(old, new) | "a,b".replace(",","-")"a-b" | |
s.split(sep) | "a,b".split(",")['a','b'] | |
s.isalpha() | "abc".isalpha() | |
s.isdigit() | "123".isdigit() | |
s.upper() | "hi".upper()"HI" | |
s.lower() | "HI".lower()"hi" |
s = "hello world"print(s.find("world")) # 6print(s.find("python")) # -1old_str = "I like apples, apples are delicious."new_str = old_str.replace("apples", "oranges")print(new_str) # I like oranges, oranges are delicious.# 拆分s = "apple, banana, cherry"print(s.split(", ")) # ['apple', 'banana', 'cherry']# 判断print("Hello".isalpha()) # Trueprint("123".isdigit()) # Trueprint("Hello123".isalpha()) # Falseprint("hello".upper()) # HELLOprint("HELLO".lower()) # helloname = 'Tom'age = 20print('我的名字是{},已经{}岁啦'.format(name, age))# 我的名字是Tom,已经20岁啦💡 更推荐使用 f-string(前面已学),更简洁:
f"我的名字是{name},已经{age}岁啦"
# 1. 计算长度str1 = "Hello, world!"print(len(str1)) # 13# 2. 替换逗号为空格str2 = "Hello, world, Python!"print(str2.replace(",", " ")) # Hello world Python!# 3. 拆分字符串str3 = "Hello, world, Python"words = str3.split(", ")print(words) # ['Hello', 'world', 'Python']# 4. 判断是否全为字母str4 = "Hello123"print(str4.isalpha()) # False列表是有序、可变的序列,可以存储任意类型的元素,用 [] 定义,元素之间用逗号分隔。
my_list = [1, 2, 3, 'a', 'b', 'c']print(my_list) # [1, 2, 3, 'a', 'b', 'c']my_list = [1, 2, 3, 4, 5]print(my_list[0]) # 1print(my_list[:4]) # [1, 2, 3, 4]print(my_list[4:]) # [5]matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print(matrix[1][1]) # 5(第二个列表的第二个元素)# append():末尾添加my_list = [1, 2, 3]my_list.append(4)print(my_list) # [1, 2, 3, 4]# insert(位置, 元素):指定位置插入my_list.insert(1, 10)print(my_list) # [1, 10, 2, 3, 4]# remove(值):删除第一个匹配的元素my_list = [1, 2, 3, 2, 4]my_list.remove(2)print(my_list) # [1, 3, 2, 4]# del 列表[下标]:删除指定位置my_list = [1, 2, 3, 4]del my_list[1]print(my_list) # [1, 3, 4]my_list = [1, 2, 3, 4, 5]#查找对应值的位置print(my_list.index(3)) # 2my_list = [1, 2, 3, 2, 4, 2]print(my_list.count(2)) # 3#查看对应值的重复次数my_list = ['chinese', 'english', 'physics']my_list[1] = 'math'print(my_list) # ['chinese', 'math', 'physics']# 获取长度my_list = [1, 2, 3, 4, 5]print(len(my_list)) # 5# 排序(原地修改)my_list = [5, 2, 9, 1, 5, 6]my_list.sort() # 升序print(my_list) # [1, 2, 5, 5, 6, 9]my_list.sort(reverse=True) # 降序print(my_list) # [9, 6, 5, 5, 2, 1]# 1. 创建购物车列表cart = ['apple', 'banana', 'orange']# 2. 添加 grapescart.append('grapes')print(cart) # ['apple', 'banana', 'orange', 'grapes']# 3. 删除 applecart.remove('apple')print(cart) # ['banana', 'orange', 'grapes']# 4. 查找 banana 的索引idx = cart.index('banana')print(idx) # 0# 5. 修改 banana 为 pearcart[0] = 'pear'print(cart) # ['pear', 'orange', 'grapes']s = "hello world",执行 print(s[5]) 输出结果是( )A. 'o'B. ' '(空格)C. 'w'D. 报错str1 = "python",执行 print(str1[2:5]) 输出结果是( )A. 'tho'B. 'th'C. 'pyt'D. 'thon'str2 = "abcdefg",执行 print(str2[::-1]) 输出结果是( )A. 'abcdefg'B. 'gfedcba'C. 'aceg'D. 'bdf'url = "https://www.taobao.com" 中 taobao 的是( )A. url[12:18]B. url[12:17]C. url[11:17]D. url[11:18]str3 = "123456789",执行 print(str3[1:8:3]) 输出结果是( )A. '2468'B. '258'C. '369'D. '147'l1 = ["x", "y", "z"]; print("+".join(l1)) 输出结果是( )A. 'xyz'B. 'x+y+z'C. 'x,y,z'D. ['x', '+', 'y', '+', 'z']str4 = "hello maiya",执行 print(str4.find("maiya")) 输出结果是( )A. 5B. 6C. 7D. -1name = "ZhangSan",请通过下标和切片完成以下操作:'Z''n''Zha''San'phone = "138-1234-5678",请通过字符串操作去掉其中的 -,最终输出 13812345678。info = " 我今年25岁,月薪8000元 ",请完成以下操作:25 和月薪数字 8000(仅需提取数字部分,无需转换类型)| B | s[5]"hello world" 中下标5是空格(h e l l o 空格 w...) | |
| C | [start:stop] 包含 start,不包含 stop | |
| A | "python"[2:5]'t', 'h', 'o' → "tho" | |
| B | [::-1]"gfedcba" | |
| D | "https://www.taobao.com"t 下标11,o 下标17(需包含),所以 [11:18] | |
| B | "123456789"[1:8:3]'2','5','8' → "258" | |
| B | "+".join(l1)"+" 连接列表元素 → "x+y+z" | |
| B | "hello maiya""maiya" 首字母 m 下标6 |
1. 字符串切片提取
name = "ZhangSan"first_char = name[0] # 'Z'last_char = name[-1] # 'n'first_three = name[:3] # 'Zha'last_three = name[-3:] # 'San'2. 去掉连字符
phone = "138-1234-5678"result = phone.replace("-", "")print(result) # 13812345678# 或使用 split + joinresult = "".join(phone.split("-"))3. 去除空格并提取数字
info = " 我今年25岁,月薪8000元 "# 去除首尾空格info_clean = info.strip()# 方法1:直接切片(已知位置)age = info_clean[3:5] # "25"salary = info_clean[9:13] # "8000"# 方法2:遍历提取所有数字(通用)age = ""salary = ""found_age = Falsefor ch in info_clean:if ch.isdigit():ifnot found_age: age += chelse: salary += chelse:if age andnot found_age: found_age = Trueprint(age, salary) # 25 8000本篇笔记涵盖了字符串和列表的核心知识:
find、replace、split、isalpha、isdigit 等)。append、insert、remove、del、index、count、sort 等)。字符串和列表是 Python 编程中使用频率最高的两种数据结构,务必多加练习。熟练掌握它们,你就能轻松处理大部分文本和集合数据。
📌 如果觉得有帮助,欢迎收藏或分享给一起学习 Python 的小伙伴~🔜 下一篇预告:字典与集合 —— 更强大的数据组织方式(键值对、去重等)。
©着迷不白 — 人生苦短,我用 Python