- 熟练使用常用方法:
upper / lower / strip / split / replace / find / format。 - 掌握三种格式化方式:
% / str.format / f-string。
二、学习路线
三、知识点讲解
1. 索引 - 字符串里每个字符都有下标,从 0 开始:"Hello" 中 H 是 0、e 是 1。 - 负数表示从末尾倒着数:-1 是最后一个字符。
2. 切片 [start:stop] - 取从 start 到 stop 之前的一段,含头不含尾。 - 省略 start 从头开始,省略 stop 到尾结束:s[7:] 取第 7 到末尾。 - 加步长 s[::2] 每隔一个取一个;s[::-1] 是经典的反转写法。
3. 常用方法(都返回新字符串,原串不变) - upper() / lower():全大 / 全小写。 - strip():去掉首尾空白(也常用来清掉用户多打的空格)。 - split(分隔符):按分隔符切成列表;如 "a,b,c".split(",") → ['a','b','c']。 - replace(旧, 新):替换子串。 - find(子串):返回子串首次出现位置,找不到返回 -1。 - format(...):占位符 {} 填入参数(旧式格式化)。
4. 三种格式化方式 - % 旧式:"我叫 %s,今年 %d 岁" % (name, age)。 - str.format:"我叫 {0},今年 {1} 岁".format(name, age)。 - f-string(推荐):f"我叫 {name},今年 {age} 岁",最直观。
5. 转义与原始字符串 - \n 换行、\t 制表符、\\ 反斜杠本身,这些叫转义序列。 - 路径里反斜杠多,写 r"C:\new\test" 这种原始字符串可让 \ 不转义,少踩坑。
四、实例代码
对应文件:day04_string.py
# Day04: 字符串处理# 知识点:索引与切片、常用方法、三种格式化方式、转义与原始字符串。text = "Hello, Python"print("原字符串:", text)# 1) 索引(下标从 0 开始;负数表示从末尾倒着数)print("第 0 个字符:", text[0]) # Hprint("第 7 个字符:", text[7]) # Pprint("倒数第 1 个字符:", text[-1]) # n# 2) 切片 [start:stop]:包含 start,不包含 stopprint("切片 [0:5]:", text[0:5]) # Helloprint("切片 [7:]:", text[7:]) # Pythonprint("步长 [::2]:", text[::2]) # Hlo yhnprint("反转 [::-1]:", text[::-1]) # nohtyP ,olleH# 3) 常用方法s = " Hello World "print("upper:", s.upper())print("lower:", s.lower())print("strip 去掉两端空格:", repr(s.strip())) # repr 让首尾空格可见地消失print("split:", "a,b,c".split(","))print("replace:", "hello".replace("l", "L"))print("find(找不到返回 -1):", "hello".find("ll"))print("format:", "{} 喜欢 {}".format("小明", "Python"))# 4) 三种格式化方式对比name = "小红"age = 20print("百分号 %:", "我叫 %s,今年 %d 岁" % (name, age))print("str.format:", "我叫 {0},今年 {1} 岁".format(name, age))print("f-string:", f"我叫 {name},今年 {age} 岁")# 5) 转义与原始字符串print("转义演示:\\n 表示换行,\\t 表示制表符")print("原始字符串 r'\\n' 不转义:", r"\n\t")# 注意:字符串本身不可变,方法都返回【新】字符串,原串不变t = "python"t2 = t.upper()print("t 没变:", t, "| 新字符串:", t2)
五、调试注意事项
- 切片下标越界不会报错,只会返回能取到的部分;但单独索引越界会报
IndexError。 split() 不传参数时默认按「任意空白」切,和传具体字符行为不同。- 方法不改原串:写了
s.upper() 却没赋回变量,原 s 还是小写。
六、运行结果提示
原字符串: Hello, Python第 0 个字符: H第 7 个字符: P倒数第 1 个字符: n切片 [0:5]: Hello切片 [7:]: Python步长 [::2]: Hlo yhn反转 [::-1]: nohtyP ,olleHupper: HELLO WORLD lower: hello world strip 去掉两端空格: 'Hello World'split: ['a', 'b', 'c']replace: heLLofind(找不到返回 -1): 2format: 小明 喜欢 Python百分号 %: 我叫 小红,今年 20 岁str.format: 我叫 小红,今年 20 岁f-string: 我叫 小红,今年 20 岁转义演示:\n 表示换行,\t 表示制表符原始字符串 r'\n' 不转义: \n\tt 没变: python | 新字符串: PYTHON
七、常见错误与避坑
- 把「索引」和「切片」混用:单索引越界报错,切片越界不报错。
- 用
+ 拼接字符串时混入数字:"分" + 95 报错,要 str(95)。 - Windows 路径忘用原始字符串或双反斜杠:
"C:\new" 里的 \n 会被当换行,写 r"C:\new" 最省心。