【Python零基础入门】第7篇:Python字符串方法大全:常用操作一网打尽
2026/4/29 18:54:26 网站建设 项目流程

🎯 学习目标

全面掌握Python字符串的各种方法,包括查找替换、分割连接、大小写转换、判断验证、填充对齐、编码解码等,成为字符串处理的高手!


📖 导语

在前两篇文章中,我们已经学习了字符串的创建、索引和切片操作。今天,我们将继续深入探索Python字符串的方法(Methods)

Python字符串提供了丰富多样的内置方法,这些方法可以帮助我们高效地处理各种文本数据。据统计,Python字符串有47个内置方法,掌握这些方法,将大大提升你的编程效率!

本文将系统性地介绍所有常用字符串方法,并通过大量实例帮助你理解和记忆。最后还有6道练习题及详细答案,帮助你巩固所学知识。


一、字符串方法概览

Python字符串是不可变类型,所有字符串方法都返回一个新的字符串,而不会修改原字符串。

1.1 方法分类

类别常用方法
大小写转换upper, lower, title, capitalize, swapcase, casefold
查找替换find, index, rfind, rindex, replace, count
分割连接split, rsplit, splitlines, join, partition, rpartition
去除空白strip, lstrip, rstrip
判断验证startswith, endswith, isalpha, isdigit, isalnum, isspace
填充对齐center, ljust, rjust, zfill, expandtabs
编码解码encode, decode
其他format, strip, translate, maketrans

二、大小写转换方法

2.1 upper() - 全大写

将字符串中的所有字母转换为大写:

text = Hello World

print(text.upper()) # 输出: HELLO WORLD

2.2 lower() - 全小写

将字符串中的所有字母转换为小写:

text = Hello World

print(text.lower()) # 输出: hello world

2.3 title() - 标题格式

将每个单词的首字母大写:

text = hello world python

print(text.title()) # 输出: Hello World Python

2.4 capitalize() - 句首大写

将字符串的第一个字符大写,其余小写:

text = hello WORLD

print(text.capitalize()) # 输出: Hello world

2.5 swapcase() - 大小写互换

大写变小写,小写变大写:

text = Hello World

print(text.swapcase()) # 输出: hELLO wORLD

2.6 casefold() - 更激进的小写

比lower()更激进,用于忽略大小写的比较:

text = HELLO WORLD

print(text.casefold()) # 输出: hello world

# 特殊字符处理

german = Straße # 德语

print(german.lower()) # straße

print(german.casefold()) # strasse

2.7 实战应用:不区分大小写的比较

user_input = Yes

if user_input.casefold() == yes:

print(用户同意) # 匹配:Yes, YES, yes


三、查找和替换方法

3.1 find() - 查找子串

查找子串第一次出现的位置,找不到返回-1:

text = Hello World, Hello Python

print(text.find(Hello)) # 输出: 0

print(text.find(Python)) # 输出: 19

print(text.find(Java)) # 输出: -1(找不到)

3.2 index() - 查找子串(报错版)

与find()类似,但找不到会抛出ValueError:

text = Hello World

print(text.index(Hello)) # 输出: 0

# print(text.index(Java)) # 报错: ValueError

3.3 rfind() 和 rindex() - 从右查找

从字符串右边开始查找:

text = Hello World, Hello Python

print(text.rfind(Hello)) # 输出: 13(第二个Hello)

print(text.rfind(o)) # 输出: 20(最后一个o)

3.4 count() - 统计出现次数

统计子串出现的次数:

text = Hello World, Hello Python

print(text.count(Hello)) # 输出: 2

print(text.count(l)) # 输出: 4

3.5 replace() - 替换子串

替换子串为另一个子串:

text = Hello World, Hello Python

print(text.replace(Hello, Hi)) # Hi World, Hi Python

print(text.replace(Hello, Hi, 1)) # Hi World, Hello Python(只替换1次)

3.6 实战应用:敏感词替换

def censor_text(text, bad_words):

for word in bad_words:

text = text.replace(word, *** * len(word))

return text

text = 这个坏蛋真是讨厌

print(censor_text(text, [坏蛋])) # 这个***真是讨厌


四、分割和连接方法

4.1 split() - 分割字符串

根据分隔符分割字符串,返回列表:

text = apple,banana,orange

fruits = text.split(,)

print(fruits) # [apple, banana, orange]

4.2 split() 限制分割次数

data = a,b,c,d,e

print(data.split(,, 2)) # [a, b, c,d,e]

4.3 rsplit() - 从右分割

从右边开始分割:

path = /usr/local/bin/python

print(path.rsplit(/, 1)) # [/usr/local/bin, python]

4.4 splitlines() - 按行分割

按换行符分割字符串:

text = Line1\nLine2\nLine3

lines = text.splitlines()

print(lines) # [Line1, Line2, Line3]

4.5 join() - 连接字符串

使用指定字符串连接列表中的元素:

fruits = [apple, banana, orange]

print(-.join(fruits)) # apple-banana-orange

print( .join(fruits)) # apple banana orange

print().join(fruits)) # applebananaorange

4.6 partition() 和 rpartition()

将字符串分成三部分(前、分隔符、后):

text = Hello-World-Python

print(text.partition(-)) # (Hello, -, World-Python)

print(text.rpartition(-)) # (Hello-World, -, Python)

4.7 实战应用:解析URL

url = https://www.example.com/path/to/page

protocol, sep, rest = url.partition(://)

print(protocol) # https

domain, sep, path = rest.partition(/)

print(domain) # www.example.com

print(path) # path/to/page


五、去除空白字符方法

5.1 strip() - 去除两端空白

去除字符串开头和结尾的空白字符(空格、制表符、换行符):

text = Hello World

print(text.strip()) # Hello World

5.2 lstrip() - 去除左边空白

text = Hello World

print(text.lstrip()) # Hello World (右边空格保留)

5.3 rstrip() - 去除右边空白

text = Hello World

print(text.rstrip()) # Hello World(左边空格保留)

5.4 去除指定字符

strip()方法可以指定要去除的字符:

text = xxxHello Worldxxx

print(text.strip(x)) # Hello World

text = 123Hello321

print(text.strip(123)) # Hello(去除1、2、3)

5.5 实战应用:清理用户输入

def clean_input(user_input):

# 去除两端空白并转为小写

return user_input.strip().lower()

email = User@Example.COM

clean_email = clean_input(email)

print(clean_email) # user@example.com


六、判断验证方法

6.1 startswith() - 检查开头

检查字符串是否以指定子串开头:

text = Hello World

print(text.startswith(Hello)) # True

print(text.startswith(Hi)) # False

6.2 endswith() - 检查结尾

检查字符串是否以指定子串结尾:

filename = document.txt

print(filename.endswith(.txt)) # True

print(filename.endswith(.pdf)) # False

6.3 isalpha() - 是否全是字母

text = Hello

print(text.isalpha()) # True

text = Hello123

print(text.isalpha()) # False

6.4 isdigit() - 是否全是数字

text = 12345

print(text.isdigit()) # True

text = 12.34

print(text.isdigit()) # False(有小数点)

6.5 isalnum() - 是否字母或数字

text = Hello123

print(text.isalnum()) # True

text = Hello 123

print(text.isalnum()) # False(有空格)

6.6 isspace() - 是否全是空白

text =

print(text.isspace()) # True

6.7 其他判断方法

print(HELLO.isupper()) # True(全大写)

print(hello.islower()) # True(全小写)

print(Hello World.istitle()) # True(标题格式)

print(123.isnumeric()) # True(可表示数字)

6.8 实战应用:文件类型检查

def check_file_type(filename):

if filename.endswith((.jpg, .jpeg, .png, .gif)):

return 图片文件

elif filename.endswith((.mp4, .avi, .mov)):

return 视频文件

elif filename.endswith((.txt, .doc, .pdf)):

return 文档文件

else:

return 未知类型

print(check_file_type(photo.jpg)) # 图片文件


七、填充对齐方法

7.1 center() - 居中

将字符串居中,两侧填充指定字符(默认空格):

text = Hello

print(text.center(20)) # Hello

print(text.center(20, -)) # --------Hello--------

7.2 ljust() - 左对齐

字符串左对齐,右侧填充:

text = Hello

print(text.ljust(20, *)) # Hello***************

7.3 rjust() - 右对齐

字符串右对齐,左侧填充:

text = Hello

print(text.rjust(20, *)) # ***************Hello

7.4 zfill() - 零填充

在数字字符串左侧填充零:

num = 42

print(num.zfill(5)) # 00042

print(num.zfill(10)) # 0000000042

7.5 expandtabs() - 制表符转空格

将制表符\t转换为空格(默认8个):

text = Name\tAge\tCity

print(text.expandtabs()) # Name Age City

print(text.expandtabs(4)) # Name Age City

7.6 实战应用:表格格式化

def format_table_row(name, age, city):

return f{name.ljust(15)}{str(age).center(10)}{city.rjust(15)}

print(format_table_row(Alice, 25, Beijing))

print(format_table_row(Bob, 30, Shanghai))

print(format_table_row(Charlie, 35, Guangzhou))


八、编码解码方法

8.1 encode() - 编码

将字符串编码为字节:

text = 你好,世界

utf8_bytes = text.encode(utf-8)

print(utf8_bytes) # b\xe4\xbd\xa0\xe5\xa5\xbd...

gbk_bytes = text.encode(gbk)

print(gbk_bytes)

8.2 decode() - 解码

将字节解码为字符串:

bytes_data = b\xe4\xbd\xa0\xe5\xa5\xbd

text = bytes_data.decode(utf-8)

print(text) # 你好

8.3 常见编码

编码说明特点
ASCII美国标准编码只支持英文,1字节
UTF-8Unicode转换格式变长编码,国际通用
GBK中文国标编码2字节,中文Windows默认
UTF-16Unicode编码2或4字节

8.4 实战应用:处理文件编码

def read_file_safe(filepath):

encodings = [utf-8, gbk, latin-1]

for enc in encodings:

try:

with open(filepath, r, encoding=enc) as f:

return f.read()

except UnicodeDecodeError:

continue

raise ValueError(无法解码文件)


九、高级字符串方法

9.1 translate() 和 maketrans() - 字符转换

创建翻译表并进行批量字符替换:

# 创建翻译表:将a换成1,b换成2,c换成3

table = str.maketrans({a: 1, b: 2, c: 3})

text = abcdef

print(text.translate(table)) # 123def

# 删除指定字符

table = str.maketrans(, , abc) # 第三个参数是要删除的

text = abcdef

print(text.translate(table)) # def

9.2 format_map() - 字典格式化

使用字典进行字符串格式化:

data = {name: Alice, age: 25}

template = Name: {name}, Age: {age}

print(template.format_map(data))

9.3 removeprefix() 和 removesuffix() - 移除前缀后缀

Python 3.9+新增:

text = test_file.txt

print(text.removeprefix(test_)) # file.txt

print(text.removesuffix(.txt)) # test_file

9.4 removeprefix() 对比 lstrip()

filename = hello.txt

print(filename.removeprefix(hel)) # lo.txt(精确匹配)

print(filename.lstrip(hel)) # o.txt(删除所有h、e、l)

9.5 字符串格式化速查表

格式示例输出
% 格式化Hello %s % nameHello Alice
format()Hello {}.format(name)Hello Alice
f-stringfHello {name}Hello Alice

十、实战案例

10.1 日志解析器

解析Apache日志格式:

log_line = 192.168.1.1 - - [10/Oct/2023:13:55:36 -0700] GET /api/users HTTP/1.1 200 1234

def parse_log(line):

parts = line.split()

return {

ip: parts[0],

timestamp: parts[3][1:],

method: parts[5][1:],

path: parts[6],

status: parts[8]

}

print(parse_log(log_line))

10.2 CSV解析器

简单CSV数据解析:

csv_line = Alice,25,Beijing,Engineer

def parse_csv(line, delimiter=,):

fields = line.split(delimiter)

return {

name: fields[0].strip(),

age: int(fields[1]),

city: fields[2].strip(),

job: fields[3].strip()

}

print(parse_csv(csv_line))

10.3 密码强度检查器

def check_password(password):

checks = {

length: len(password) >= 8,

uppercase: any(c.isupper() for c in password),

lowercase: any(c.islower() for c in password),

digit: any(c.isdigit() for c in password),

special: any(not c.isalnum() for c in password)

}

score = sum(checks.values())

strength = [极弱, 弱, 中等, 强, 很强, 完美]

return strength[score], checks

print(check_password(Abc123!@#))

10.4 文本统计工具

def text_stats(text):

words = text.split()

return {

字符数: len(text),

单词数: len(words),

行数: text.count(\n) + 1,

数字数: sum(c.isdigit() for c in text),

字母数: sum(c.isalpha() for c in text)

}

sample = Hello World! This is Python 3.12.

print(text_stats(sample))


十一、小结

今天我们全面学习了Python字符串的各种方法:

✅ 大小写转换:upper(), lower(), title(), capitalize(), swapcase(), casefold()

✅ 查找替换:find(), index(), rfind(), rindex(), replace(), count()

✅ 分割连接:split(), rsplit(), splitlines(), join(), partition(), rpartition()

✅ 去除空白:strip(), lstrip(), rstrip()

✅ 判断验证:startswith(), endswith(), isalpha(), isdigit(), isalnum(), isspace()

✅ 填充对齐:center(), ljust(), rjust(), zfill(), expandtabs()

✅ 编码解码:encode(), decode()

✅ 高级方法:translate(), maketrans(), format_map(), removeprefix(), removesuffix()

💡 学习方法建议:

1. 不需要一次性记住所有方法,重点是知道Python提供了这些功能

2. 遇到问题时,可以查阅官方文档或使用dir()函数查看所有方法

3. 多写代码,在实际项目中练习使用这些方法

4. 注意字符串是不可变的,所有方法都返回新字符串

🔧 快速查阅:

# 查看字符串所有方法

print([m for m in dir(str) if not m.startswith(_)])


十二、课后练习与答案

练习1:大小写转换

题目:

给定字符串 text = python programming language

1. 将其转换为全大写

2. 将其转换为标题格式(每个单词首字母大写)

3. 将其转换为句首大写(只有第一个字母大写)

答案:

text = python programming language

# 1. 全大写

print(text.upper()) # PYTHON PROGRAMMING LANGUAGE

# 2. 标题格式

print(text.title()) # Python Programming Language

# 3. 句首大写

print(text.capitalize()) # Python programming language

练习2:查找替换

题目:

给定字符串:article = Python is great. Python is easy. Python is powerful.

1. 统计 Python 出现的次数

2. 将所有 Python 替换为 Java(只替换前2个)

3. 查找第一个 is 的位置

答案:

article = Python is great. Python is easy. Python is powerful.

# 1. 统计出现次数

count = article.count(Python)

print(fPython出现了{count}次) # Python出现了3次

# 2. 替换前2个

new_article = article.replace(Python, Java, 2)

print(new_article) # Java is great. Java is easy. Python is powerful.

# 3. 查找第一个is的位置

pos = article.find(is)

print(f第一个is在位置:{pos}) # 第一个is在位置:7

练习3:分割连接

题目:

1. 将 data-science-machine-learning 按 - 分割

2. 将分割后的结果用 / 连接

3. 使用 partition() 提取文件名和扩展名:document.pdf

答案:

# 1. 分割

text = data-science-machine-learning

parts = text.split(-)

print(parts) # [data, science, machine, learning]

# 2. 用/连接

result = / .join(parts)

print(result) # data/science/machine/learning

# 3. 提取文件名和扩展名

filename = document.pdf

name, dot, ext = filename.partition(.)

print(f文件名:{name}) # 文件名:document

print(f扩展名:{ext}) # 扩展名:pdf

练习4:判断验证

题目:

编写函数 validate_username(username):

- 长度至少3个字符

- 只能包含字母、数字和下划线

- 不能以数字开头

返回 True 或 False

答案:

def validate_username(username):

# 长度至少3个字符

if len(username) < 3:

return False

# 不能以数字开头

if username[0].isdigit():

return False

# 只能包含字母、数字和下划线

for char in username:

if not (char.isalnum() or char == _):

return False

return True

# 测试

print(validate_username(user_123)) # True

print(validate_username(12abc)) # False(数字开头)

print(validate_username(ab)) # False(太短)

print(validate_username(user-name)) # False(包含-)

练习5:填充对齐

题目:

格式化输出一个产品列表:

products = [(iPhone, 9999), (iPad, 4999), (MacBook, 12999)]

要求:

- 产品名左对齐,宽度20

- 价格右对齐,宽度10,前面加¥符号

答案:

products = [(iPhone, 9999), (iPad, 4999), (MacBook, 12999)]

print(产品名称.ljust(20) + 价格.rjust(10))

print(- * 30)

for name, price in products:

# 产品名左对齐,宽度20

name_formatted = name.ljust(20)

# 价格右对齐,宽度10,前面加¥

price_formatted = f¥{price}.rjust(10)

print(name_formatted + price_formatted)

# 输出:

# 产品名称 价格

# ------------------------------

# iPhone ¥9999

# iPad ¥4999

# MacBook ¥12999

练习6:综合练习

题目:

编写一个函数 clean_and_normalize(text):

1. 去除两端空白

2. 将多个连续空格替换为单个空格

3. 将所有字母转为小写

4. 将句子首字母大写

答案:

def clean_and_normalize(text):

# 1. 去除两端空白

text = text.strip()

# 2. 将多个连续空格替换为单个空格

# 先按空格分割,再重新连接

words = text.split()

text = .join(words)

# 3. 将所有字母转为小写

text = text.lower()

# 4. 将句子首字母大写

text = text.capitalize()

return text

# 测试

messy_text = Hello WORLD !!! This IS a TEST.

clean_text = clean_and_normalize(messy_text)

print(clean_text) # Hello world !!! this is a test.

# 方法二:使用正则表达式(更简洁)

import re

def clean_and_normalize_v2(text):

# 去除两端空白并转为小写

text = text.strip().lower()

# 将多个空格替换为单个空格

text = re.sub(r\s+, , text)

# 首字母大写

text = text.capitalize()

return text

print(clean_and_normalize_v2(messy_text))


十三、下篇预告

第8篇:《Python布尔类型与空值:True、False和None》

在下一篇中,我们将学习:

- 布尔类型的概念和应用

- 真值测试和布尔运算

- None的含义和用法

- 类型转换:bool()函数

- 布尔类型在条件判断中的应用

敬请期待!


📌系列文章目录:点击关注,持续更新中...


如果觉得有帮助,请点赞 👍 + 收藏 ⭐ + 关注 ❤️

你的支持是我持续创作的动力!


本文为本系列第7篇,带你从零基础到Python实战!

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询