)
Python中字符串的操作超详细版前言字符串是Python中最常用的数据类型之一无论是处理文本数据、用户输入还是文件读写都离不开字符串操作。本文将系统讲解Python字符串的7大核心知识点从基础定义到高级操作一篇文章带你彻底掌握。一、字符串的定义在Python中字符串可以使用单引号、双引号或三引号来定义。1.1 基本定义方式python# 单引号 str1 Hello Python # 双引号推荐可以包含单引号 str2 Im a student # 三引号多行字符串 str3 这是第一行 这是第二行 这是第三行 # 三引号也可以用来写注释或文档字符串 def test(): 这是一个函数的文档字符串 pass print(str1) # Hello Python print(str2) # Im a student print(str3) # 输出三行文字1.2 字符串的两种类型python# 普通字符串默认 s1 hello # 字节字符串以b开头 s2 bhello # 用于网络传输或二进制数据 # 原始字符串以r开头不转义 s3 rC:\Users\name\Desktop # 路径中\不会被转义 print(s3) # C:\Users\name\Desktop二、转义字符转义字符是以反斜杠\开头的特殊字符用来表示无法直接输入或容易混淆的字符。2.1 常用转义字符转义字符含义\n换行\t制表符Tab键\\反斜杠本身\单引号\双引号\r回车\b退格2.2 示例代码python# 换行 print(第一行\n第二行) # 输出 # 第一行 # 第二行 # 制表符 print(姓名\t年龄\t性别) print(张三\t20\t男) # 输出 # 姓名 年龄 性别 # 张三 20 男 # 反斜杠 print(C:\\Users\\Desktop) # C:\Users\Desktop # 引号 print(I\m a teacher) # Im a teacher print(He said: \Hello\) # He said: Hello # 使用原始字符串 r 避免转义 path rC:\new_folder\test.txt print(path) # C:\new_folder\test.txt\n不会被转义三、字符串格式化Python提供了多种字符串格式化方式让变量动态嵌入字符串中。3.1 % 格式化旧式pythonname 张三 age 20 score 85.5 print(姓名%s年龄%d成绩%.1f % (name, age, score)) # 输出姓名张三年龄20成绩85.5 # 常用占位符 # %s - 字符串 # %d - 整数 # %f - 浮点数%.2f 保留两位小数 # %x - 十六进制3.2 format() 方法推荐pythonname 张三 age 20 score 85.5 # 按位置 print(姓名{}年龄{}成绩{}.format(name, age, score)) # 按索引 print(姓名{0}年龄{1}成绩{2}.format(name, age, score)) # 按关键字最清晰 print(姓名{n}年龄{a}成绩{s}.format(nname, aage, sscore)) # 对齐与填充 print({:10}.format(左对齐)) # 左对齐宽度10 print({:10}.format(右对齐)) # 右对齐 print({:^10}.format(居中)) # 居中对齐 print({:*^10}.format(居中)) # 用*填充居中3.3 f-stringPython 3.6最推荐pythonname 张三 age 20 score 85.5 # 直接在字符串中用 {} 嵌入变量 print(f姓名{name}年龄{age}成绩{score}) # 姓名张三年龄20成绩85.5 # 可以执行表达式 print(f明年年龄{age 1}) # 可以调用方法 print(f姓名大写{name.upper()}) # 格式控制 print(f成绩保留两位{score:.2f}) print(f居中{居中:*^10}) # ****居中****3.4 三种格式化方式对比方式写法适用场景% 格式化%s % name旧代码维护format(){}.format(name)通用兼容f-stringf{name}Python 3.6 首选四、索引Index字符串中的每个字符都有一个位置编号从0开始正向编号或从-1开始反向编号。4.1 正向索引从0开始pythons Hello Python # 正向索引0 1 2 3 4 5 6 7 8 9 10 11 # H e l l o P y t h o n print(s[0]) # H print(s[1]) # e print(s[6]) # P print(s[11]) # n4.2 反向索引从-1开始pythons Hello Python # 反向索引-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 # H e l l o P y t h o n print(s[-1]) # n最后一个字符 print(s[-2]) # o print(s[-6]) # P4.3 索引使用注意事项pythons Hello # ✅ 索引范围在 0 到 len(s)-1 之间 print(s[4]) # o # ❌ IndexError索引越界 # print(s[5]) # 报错 # 获取字符串长度 print(len(s)) # 5 print(s[len(s) - 1]) # o最后一个字符五、切片Slicing切片可以从字符串中截取一部分语法为s[start:end:step]。5.1 基本切片语法pythons Hello Python # s[起始:结束:步长] # 包含起始位置不包含结束位置 print(s[0:5]) # Hello取索引0-4 print(s[6:12]) # Python取索引6-11 print(s[:5]) # Hello省略起始从0开始 print(s[6:]) # Python省略结束到末尾 print(s[:]) # Hello Python复制整个字符串5.2 步长Steppythons Hello Python print(s[::2]) # HloPto每隔一个取一个 print(s[1::2]) # el yhn从索引1开始每隔一个取一个 print(s[::-1]) # nohtyP olleH反转字符串5.3 切片中负索引的使用pythons Hello Python print(s[-6:]) # Python取后6个字符 print(s[:-7]) # Hel去后7个字符 print(s[-6:-1]) # Pytho索引-6到-25.4 经典切片示例pythons abcdefghijklmnopqrstuvwxyz # 取前10个 print(s[:10]) # abcdefghij # 取后5个 print(s[-5:]) # vwxyz # 取偶数位置的字符 print(s[::2]) # acegikmoqsuwy # 反转字符串 print(s[::-1]) # zyxwvutsrqponmlkjihgfedcba # 判断是否为回文正反相同 text racecar print(text text[::-1]) # True六、遍历字符串遍历字符串即逐个访问字符串中的每个字符。6.1 for 循环直接遍历最常用pythons Hello for char in s: print(char) # 输出H e l l o每个字符一行 # 统计某个字符出现次数 count 0 for char in s: if char l: count 1 print(count) # 26.2 通过索引遍历使用 rangepythons Hello for i in range(len(s)): print(f索引{i}{s[i]}) # 输出 # 索引0H # 索引1e # 索引2l # 索引3l # 索引4o6.3 同时获取索引和字符enumeratepythons Hello for i, char in enumerate(s): print(f索引{i}{char}) # 输出同上 # 指定起始索引 for i, char in enumerate(s, start1): print(f第{i}个字符{char}) # 第1个字符H # 第2个字符e # ...6.4 while 循环遍历pythons Hello i 0 while i len(s): print(s[i]) i 16.5 遍历场景示例python# 1. 找出所有 a 的位置 s abcabcabc for i, char in enumerate(s): if char a: print(i, end ) # 0 3 6 print() # 2. 统计大小写字母数量 text Hello Python upper lower 0 for char in text: if char.isupper(): upper 1 elif char.islower(): lower 1 print(f大写{upper}小写{lower}) # 大写2小写8 # 3. 去除数字 text a1b2c3d4 result for char in text: if not char.isdigit(): result char print(result) # abcd七、字符串常用方法超全汇总7.1 查找相关方法说明示例find(sub)查找子串返回索引找不到返回-1hello.find(l)→ 2index(sub)查找子串返回索引找不到报错hello.index(l)→ 2rfind(sub)从右查找返回索引hello.rfind(l)→ 3rindex(sub)从右查找找不到报错hello.rindex(l)→ 3count(sub)统计子串出现次数hello.count(l)→ 2startswith(prefix)是否以指定前缀开头hello.startswith(he)→ Trueendswith(suffix)是否以指定后缀结尾hello.endswith(lo)→ Truepythontext abcabcabc print(text.find(a)) # 0 print(text.find(a, 2)) # 3从索引2开始找 print(text.rfind(a)) # 6 print(text.index(b)) # 1 print(text.count(c)) # 3 print(text.startswith(ab)) # True print(text.endswith(bc)) # True7.2 判断相关方法说明示例isalpha()是否全为字母hello.isalpha()→ Trueisdigit()是否全为数字123.isdigit()→ Trueisalnum()是否全为字母或数字abc123.isalnum()→ Trueisspace()是否全为空白字符 .isspace()→ Trueisupper()是否全为大写HELLO.isupper()→ Trueislower()是否全为小写hello.islower()→ Trueistitle()是否为标题格式Hello World.istitle()→ Truepythonprint(Python123.isalnum()) # True print(123.isdigit()) # True print(Hello.isalpha()) # True print(Hello World.istitle()) # True每个单词首字母大写7.3 大小写转换方法说明示例upper()转为大写hello.upper()→ HELLOlower()转为小写HELLO.lower()→ hellocapitalize()首字母大写hello.capitalize()→ Hellotitle()每个单词首字母大写hello world.title()→ Hello Worldswapcase()大小写互换Hello.swapcase()→ hELLOpythontext hello WORLD print(text.upper()) # HELLO WORLD print(text.lower()) # hello world print(text.capitalize()) # Hello world print(text.title()) # Hello World print(text.swapcase()) # HELLO world7.4 去除空白方法说明示例strip()去除两端空白 hello .strip()→ hellolstrip()去除左侧空白 hello.lstrip()→ hellorstrip()去除右侧空白hello .rstrip()→ hellopythontext \t\nhello world\t\n print(text.strip()) # hello world print(text.lstrip()) # hello world 去除左侧保留右侧 print(text.rstrip()) # hello world去除右侧保留左侧 # 去除指定字符 print(***hello***.strip(*)) # hello7.5 分割与连接方法说明示例split(sep)按分隔符分割成列表a,b,c.split(,)→ [a,b,c]rsplit(sep)从右分割a,b,c.rsplit(,, 1)→ [a,b,c]splitlines()按换行符分割a\nb.splitlines()→ [a,b]join(iterable)用字符串连接列表,.join([a,b,c])→ a,b,cpython# split - 字符串 → 列表 s 苹果,香蕉,橘子 print(s.split(,)) # [苹果, 香蕉, 橘子] s a,b,c,d,e print(s.split(,, 2)) # [a, b, c,d,e]只分割前2次 # splitlines - 处理多行文本 text 第一行\n第二行\n第三行 print(text.splitlines()) # [第一行, 第二行, 第三行] # join - 列表 → 字符串 fruits [苹果, 香蕉, 橘子] print(.join(fruits)) # 苹果香蕉橘子 print(.join(fruits)) # 苹果香蕉橘子 # 数字列表需要转成字符串才能join nums [1, 2, 3] print(.join(str(n) for n in nums)) # 1237.6 替换与填充方法说明示例replace(old, new)替换子串hello.replace(l,x)→ hexxocenter(width, fill)居中填充hello.center(10,*)→ hello*ljust(width, fill)左对齐填充hello.ljust(10,*)→ hello*****rjust(width, fill)右对齐填充hello.rjust(10,*)→ *****hellozfill(width)右对齐用0填充42.zfill(5)→ 00042python# replace text Hello World print(text.replace(World, Python)) # Hello Python print(text.replace(l, L)) # HeLLo WorLd print(text.replace(l, L, 2)) # HeLLo World只替换前2个 # 填充对齐 print(hello.center(11, *)) # ***hello*** print(hello.ljust(10, -)) # hello----- print(hello.rjust(10, -)) # -----hello print(42.zfill(6)) # 0000427.7 其他实用方法方法说明示例len(s)获取长度内置函数len(hello)→ 5max(s)获取最大字符max(abc)→ cmin(s)获取最小字符min(abc)→ ain判断是否包含he in hello→ Truenot in判断是否不包含hi not in hello→ Truepythontext Hello Python print(len(text)) # 12 print(Python in text) # True print(Java not in text) # True print(max(text)) # y按ASCII码比较 print(min(text)) # 空格ASCII码最小八、综合实战案例8.1 统计字符串中每个字符出现的次数pythontext hello world count_dict {} for char in text: if char ! : # 不统计空格 count_dict[char] count_dict.get(char, 0) 1 print(count_dict) # {h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1}8.2 判断是否为回文忽略大小写和空格pythondef is_palindrome(text): # 去除空格并转为小写 clean text.replace( , ).lower() return clean clean[::-1] print(is_palindrome(A man a plan a canal Panama)) # True print(is_palindrome(racecar)) # True print(is_palindrome(hello)) # False8.3 提取字符串中的所有数字pythontext abc123def456ghi789 numbers .join(char for char in text if char.isdigit()) print(numbers) # 1234567898.4 字符串加密凯撒密码pythondef caesar_cipher(text, shift): result for char in text: if char.isalpha(): # 确定基准ASCII码A或a base ord(A) if char.isupper() else ord(a) # 移位并保持循环 result chr((ord(char) - base shift) % 26 base) else: result char return result text Hello World encrypted caesar_cipher(text, 3) print(encrypted) # Khoor Zruog decrypted caesar_cipher(encrypted, -3) print(decrypted) # Hello World8.5 格式化输出表格pythonstudents [ [张三, 20, 85], [李四, 22, 92], [王五, 19, 78] ] print(姓名\t年龄\t成绩) print(- * 20) for name, age, score in students: print(f{name}\t{age}\t{score}) # 输出 # 姓名 年龄 成绩 # -------------------- # 张三 20 85 # 李四 22 92 # 王五 19 78九、常见错误与注意事项9.1 字符串不可变性pythons hello # ❌ 错误字符串不可变 # s[0] H # TypeError # ✅ 正确创建新字符串 s H s[1:] # Hello9.2 索引越界pythons hello # ❌ print(s[5]) # IndexError # ✅ 先判断长度 if len(s) 5: print(s[5])9.3 字符串拼接性能python# ❌ 大量拼接时效率低 result for i in range(10000): result str(i) # 不推荐 # ✅ 使用 join result .join(str(i) for i in range(10000)) # 推荐9.4 比较字符串时注意大小写python# ❌ 大小写不敏感比较会出错 print(Hello hello) # False # ✅ 统一转为大小写再比较 print(Hello.lower() hello.lower()) # True总结本文详细介绍了Python字符串的7大核心知识点知识点要点定义单引号、双引号、三引号、原始字符串转义\n、\t、\\等格式化%格式化、format()、f-string索引正向从0开始反向从-1开始切片s[start:end:step]灵活截取遍历for循环、enumerate、索引遍历常用方法查找、判断、转换、分割、替换、填充重点掌握f-string是最推荐的格式化方式切片是Python独有的强大特性join比字符串拼接更高效split和join是处理字符串与列表转换的黄金搭档希望这篇教程能帮助你全面掌握Python字符串操作如果觉得有用欢迎点赞、收藏、评论你的支持是我持续创作的动力下一篇预告Python列表的完全指南敬请期待