Python中字符串的操作(超详细版)
前言
字符串是Python中最常用的数据类型之一,无论是处理文本数据、用户输入,还是文件读写,都离不开字符串操作。本文将系统讲解Python字符串的7大核心知识点,从基础定义到高级操作,一篇文章带你彻底掌握。
一、字符串的定义
在Python中,字符串可以使用单引号、双引号或三引号来定义。
1.1 基本定义方式
python
# 单引号 str1 = 'Hello Python' # 双引号(推荐,可以包含单引号) str2 = "I'm a student" # 三引号(多行字符串) str3 = """这是第一行 这是第二行 这是第三行""" # 三引号也可以用来写注释或文档字符串 def test(): """这是一个函数的文档字符串""" pass print(str1) # Hello Python print(str2) # I'm a student print(str3) # 输出三行文字
1.2 字符串的两种类型
python
# 普通字符串(默认) s1 = "hello" # 字节字符串(以b开头) s2 = b"hello" # 用于网络传输或二进制数据 # 原始字符串(以r开头,不转义) s3 = r"C:\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') # I'm a teacher print("He said: \"Hello\"") # He said: "Hello" # 使用原始字符串 r 避免转义 path = r"C:\new_folder\test.txt" print(path) # C:\new_folder\test.txt(\n不会被转义)三、字符串格式化
Python提供了多种字符串格式化方式,让变量动态嵌入字符串中。
3.1 % 格式化(旧式)
python
name = "张三" age = 20 score = 85.5 print("姓名:%s,年龄:%d,成绩:%.1f" % (name, age, score)) # 输出:姓名:张三,年龄:20,成绩:85.5 # 常用占位符 # %s - 字符串 # %d - 整数 # %f - 浮点数(%.2f 保留两位小数) # %x - 十六进制3.2 format() 方法(推荐)
python
name = "张三" age = 20 score = 85.5 # 按位置 print("姓名:{},年龄:{},成绩:{}".format(name, age, score)) # 按索引 print("姓名:{0},年龄:{1},成绩:{2}".format(name, age, score)) # 按关键字(最清晰) print("姓名:{n},年龄:{a},成绩:{s}".format(n=name, a=age, s=score)) # 对齐与填充 print("{:<10}".format("左对齐")) # 左对齐,宽度10 print("{:>10}".format("右对齐")) # 右对齐 print("{:^10}".format("居中")) # 居中对齐 print("{:*^10}".format("居中")) # 用*填充居中3.3 f-string(Python 3.6+,最推荐)
python
name = "张三" 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-string | f"{name}" | Python 3.6+ 首选 |
四、索引(Index)
字符串中的每个字符都有一个位置编号,从0开始正向编号,或从-1开始反向编号。
4.1 正向索引(从0开始)
python
s = "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]) # n
4.2 反向索引(从-1开始)
python
s = "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]) # P
4.3 索引使用注意事项
python
s = "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 基本切片语法
python
s = "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 步长(Step)
python
s = "Hello Python" print(s[::2]) # HloPto(每隔一个取一个) print(s[1::2]) # el yhn(从索引1开始,每隔一个取一个) print(s[::-1]) # nohtyP olleH(反转字符串)
5.3 切片中负索引的使用
python
s = "Hello Python" print(s[-6:]) # Python(取后6个字符) print(s[:-7]) # Hel(去后7个字符) print(s[-6:-1]) # Pytho(索引-6到-2)
5.4 经典切片示例
python
s = "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 循环直接遍历(最常用)
python
s = "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) # 2
6.2 通过索引遍历(使用 range)
python
s = "Hello" for i in range(len(s)): print(f"索引{i}:{s[i]}") # 输出: # 索引0:H # 索引1:e # 索引2:l # 索引3:l # 索引4:o6.3 同时获取索引和字符(enumerate)
python
s = "Hello" for i, char in enumerate(s): print(f"索引{i}:{char}") # 输出同上 # 指定起始索引 for i, char in enumerate(s, start=1): print(f"第{i}个字符:{char}") # 第1个字符:H # 第2个字符:e # ...6.4 while 循环遍历
python
s = "Hello" i = 0 while i < len(s): print(s[i]) i += 1
6.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) | 查找子串,返回索引,找不到返回-1 | "hello".find("l")→ 2 |
index(sub) | 查找子串,返回索引,找不到报错 | "hello".index("l")→ 2 |
rfind(sub) | 从右查找,返回索引 | "hello".rfind("l")→ 3 |
rindex(sub) | 从右查找,找不到报错 | "hello".rindex("l")→ 3 |
count(sub) | 统计子串出现次数 | "hello".count("l")→ 2 |
startswith(prefix) | 是否以指定前缀开头 | "hello".startswith("he")→ True |
endswith(suffix) | 是否以指定后缀结尾 | "hello".endswith("lo")→ True |
python
text = "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()→ True |
isdigit() | 是否全为数字 | "123".isdigit()→ True |
isalnum() | 是否全为字母或数字 | "abc123".isalnum()→ True |
isspace() | 是否全为空白字符 | " ".isspace()→ True |
isupper() | 是否全为大写 | "HELLO".isupper()→ True |
islower() | 是否全为小写 | "hello".islower()→ True |
istitle() | 是否为标题格式 | "Hello World".istitle()→ True |
python
print("Python123".isalnum()) # True print("123".isdigit()) # True print("Hello".isalpha()) # True print("Hello World".istitle()) # True(每个单词首字母大写)7.3 大小写转换
| 方法 | 说明 | 示例 |
|---|---|---|
upper() | 转为大写 | "hello".upper()→ "HELLO" |
lower() | 转为小写 | "HELLO".lower()→ "hello" |
capitalize() | 首字母大写 | "hello".capitalize()→ "Hello" |
title() | 每个单词首字母大写 | "hello world".title()→ "Hello World" |
swapcase() | 大小写互换 | "Hello".swapcase()→ "hELLO" |
python
text = "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 world
7.4 去除空白
| 方法 | 说明 | 示例 |
|---|---|---|
strip() | 去除两端空白 | " hello ".strip()→ "hello" |
lstrip() | 去除左侧空白 | " hello".lstrip()→ "hello" |
rstrip() | 去除右侧空白 | "hello ".rstrip()→ "hello" |
python
text = " \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,c" |
python
# 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")→ "hexxo" |
center(width, fill) | 居中填充 | "hello".center(10,'*')→ "hello*" |
ljust(width, fill) | 左对齐填充 | "hello".ljust(10,'*')→ "hello*****" |
rjust(width, fill) | 右对齐填充 | "hello".rjust(10,'*')→ "*****hello" |
zfill(width) | 右对齐用0填充 | "42".zfill(5)→ "00042" |
python
# 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")→ 5 |
max(s) | 获取最大字符 | max("abc")→ 'c' |
min(s) | 获取最小字符 | min("abc")→ 'a' |
in | 判断是否包含 | "he" in "hello"→ True |
not in | 判断是否不包含 | "hi" not in "hello"→ True |
python
text = "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 统计字符串中每个字符出现的次数
python
text = "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 判断是否为回文(忽略大小写和空格)
python
def 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 提取字符串中的所有数字
python
text = "abc123def456ghi789" numbers = ''.join(char for char in text if char.isdigit()) print(numbers) # 123456789
8.4 字符串加密(凯撒密码)
python
def 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 格式化输出表格
python
students = [ ["张三", 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 字符串不可变性
python
s = "hello" # ❌ 错误:字符串不可变 # s[0] = "H" # TypeError # ✅ 正确:创建新字符串 s = "H" + s[1:] # Hello
9.2 索引越界
python
s = "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列表的完全指南,敬请期待!