news 2026/7/18 3:28:56

Python 字符串模块方法全解析(附带注释与案例)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Python 字符串模块方法全解析(附带注释与案例)

1. 字符串基础操作

Python 的字符串(str)是不可变序列,提供了丰富的内置方法用于文本处理。以下汇总了字符串模块中的所有方法,每个方法都附带注释说明和实用案例。

2. 大小写转换方法

2.1 str.capitalize()

功能:将字符串的第一个字符转换为大写,其余字符转换为小写。

案例:

text = "hello WORLD" result = text.capitalize() print(result) # 输出: Hello world

2.2 str.title()

功能:返回"标题化"的字符串,即每个单词的首字母大写,其余字母小写。

案例:

text = "python programming guide" result = text.title() print(result) # 输出: Python Programming Guide

2.3 str.upper()

功能:将字符串中的所有字符转换为大写。

案例:

text = "Hello Python" result = text.upper() print(result) # 输出: HELLO PYTHON

2.4 str.lower()

功能:将字符串中的所有字符转换为小写。

案例:

text = "HELLO PYTHON" result = text.lower() print(result) # 输出: hello python

2.5 str.swapcase()

功能:将字符串中大写转换为小写,小写转换为大写。

案例:

text = "Hello World" result = text.swapcase() print(result) # 输出: hELLO wORLD

2.6 str.casefold()

功能:返回字符串的 casefolded 副本,用于无大小写比较(比 lower() 更彻底)。

案例:

text1 = "Straße" text2 = "STRASSE" print(text1.casefold() == text2.casefold()) # 输出: True

3. 查找与替换方法

3.1 str.find(sub[, start[, end]])

功能:返回子字符串 sub 在字符串中第一次出现的索引,如果未找到则返回 -1。

案例:

text = "hello world" index = text.find("world") print(index) # 输出: 6

3.2 str.rfind(sub[, start[, end]])

功能:返回子字符串 sub 在字符串中最后一次出现的索引,如果未找到则返回 -1。

案例:

text = "hello world, hello python" index = text.rfind("hello") print(index) # 输出: 13

3.3 str.index(sub[, start[, end]])

功能:与 find() 类似,但如果未找到子字符串会引发 ValueError。

案例:

text = "hello world" try: index = text.index("world") print(index) # 输出: 6 except ValueError: print("未找到子字符串")

3.4 str.rindex(sub[, start[, end]])

功能:与 rfind() 类似,但如果未找到子字符串会引发 ValueError。

案例:

text = "hello world, hello python" index = text.rindex("hello") print(index) # 输出: 13

3.5 str.count(sub[, start[, end]])

功能:返回子字符串 sub 在字符串中出现的次数。

案例:

text = "banana" count = text.count("na") print(count) # 输出: 2

3.6 str.replace(old, new[, count])

功能:返回字符串的副本,其中所有出现的子字符串 old 都被替换为 new。

案例:

text = "hello world" new_text = text.replace("world", "Python") print(new_text) # 输出: hello Python

4. 字符串判断方法

4.1 str.startswith(prefix[, start[, end]])

功能:检查字符串是否以指定的前缀开头。

案例:

text = "hello world" result = text.startswith("hello") print(result) # 输出: True

4.2 str.endswith(suffix[, start[, end]])

功能:检查字符串是否以指定的后缀结尾。

案例:

text = "hello.py" result = text.endswith(".py") print(result) # 输出: True

4.3 str.isalnum()

功能:检查字符串是否只包含字母和数字。

案例:

text1 = "Python3" text2 = "Python 3" print(text1.isalnum()) # 输出: True print(text2.isalnum()) # 输出: False(包含空格)

4.4 str.isalpha()

功能:检查字符串是否只包含字母。

案例:

text1 = "Python" text2 = "Python3" print(text1.isalpha()) # 输出: True print(text2.isalpha()) # 输出: False(包含数字)

4.5 str.isdigit()

功能:检查字符串是否只包含数字。

案例:

text1 = "12345" text2 = "123.45" print(text1.isdigit()) # 输出: True print(text2.isdigit()) # 输出: False(包含小数点)

4.6 str.isdecimal()

功能:检查字符串是否只包含十进制数字字符。

案例:

text1 = "123" text2 = "½" print(text1.isdecimal()) # 输出: True print(text2.isdecimal()) # 输出: False

4.7 str.isnumeric()

功能:检查字符串是否只包含数字字符(包括罗马数字、分数等)。

案例:

text1 = "123" text2 = "½" text3 = "Ⅳ" print(text1.isnumeric()) # 输出: True print(text2.isnumeric()) # 输出: True print(text3.isnumeric()) # 输出: True

4.8 str.islower()

功能:检查字符串中所有字母字符是否都是小写。

案例:

text1 = "hello" text2 = "Hello" print(text1.islower()) # 输出: True print(text2.islower()) # 输出: False

4.9 str.isupper()

功能:检查字符串中所有字母字符是否都是大写。

案例:

text1 = "HELLO" text2 = "Hello" print(text1.isupper()) # 输出: True print(text2.isupper()) # 输出: False

4.10 str.isspace()

功能:检查字符串是否只包含空白字符。

案例:

text1 = " " text2 = "hello" print(text1.isspace()) # 输出: True print(text2.isspace()) # 输出: False

4.11 str.istitle()

功能:检查字符串是否为标题化字符串(每个单词首字母大写)。

案例:

text1 = "Python Programming" text2 = "python programming" print(text1.istitle()) # 输出: True print(text2.istitle()) # 输出: False

5. 字符串格式化方法

5.1 str.format(*args, **kwargs)

功能:执行字符串格式化操作。

案例:

name = "Alice" age = 25 text = "My name is {} and I'm {} years old.".format(name, age) print(text) # 输出: My name is Alice and I'm 25 years old.

5.2 str.format_map(mapping)

功能:使用映射对象执行字符串格式化。

案例:

data = {"name": "Bob", "age": 30} text = "Name: {name}, Age: {age}".format_map(data) print(text) # 输出: Name: Bob, Age: 30

5.3 f-string(Python 3.6+)

功能:格式化字符串字面值,在字符串前加 f 或 F,使用 {} 包含表达式。

案例:

name = "Charlie" age = 35 text = f"My name is {name} and I'm {age} years old." print(text) # 输出: My name is Charlie and I'm 35 years old.

6. 字符串分割与连接

6.1 str.split(sep=None, maxsplit=-1)

功能:使用分隔符 sep 分割字符串,返回列表。

案例:

text = "apple,banana,orange" result = text.split(",") print(result) # 输出: ['apple', 'banana', 'orange']

6.2 str.rsplit(sep=None, maxsplit=-1)

功能:从右边开始分割字符串。

案例:

text = "apple,banana,orange" result = text.rsplit(",", 1) print(result) # 输出: ['apple,banana', 'orange']

6.3 str.splitlines([keepends])

功能:按行分割字符串,返回各行作为元素的列表。

案例:

text = "Line 1\nLine 2\r\nLine 3" result = text.splitlines() print(result) # 输出: ['Line 1', 'Line 2', 'Line 3']

6.4 str.partition(sep)

功能:在 sep 首次出现的位置分割字符串,返回一个 3 元组。

案例:

text = "hello-world-python" result = text.partition("-") print(result) # 输出: ('hello', '-', 'world-python')

6.5 str.rpartition(sep)

功能:在 sep 最后一次出现的位置分割字符串,返回一个 3 元组。

案例:

text = "hello-world-python" result = text.rpartition("-") print(result) # 输出: ('hello-world', '-', 'python')

6.6 str.join(iterable)

功能:将可迭代对象中的字符串元素连接成一个字符串。

案例:

words = ["Python", "is", "awesome"] result = " ".join(words) print(result) # 输出: Python is awesome

7. 字符串修剪与填充

7.1 str.strip([chars])

功能:移除字符串开头和结尾的指定字符(默认为空白字符)。

案例:

text = " hello world " result = text.strip() print(result) # 输出: "hello world"

7.2 str.lstrip([chars])

功能:移除字符串开头的指定字符(默认为空白字符)。

案例:

text = " hello world " result = text.lstrip() print(result) # 输出: "hello world "

7.3 str.rstrip([chars])

功能:移除字符串结尾的指定字符(默认为空白字符)。

案例:

text = " hello world " result = text.rstrip() print(result) # 输出: " hello world"

7.4 str.ljust(width[, fillchar])

功能:返回左对齐的字符串,并使用 fillchar 填充至指定宽度。

案例:

text = "hello" result = text.ljust(10, "*") print(result) # 输出: "hello*****"

7.5 str.rjust(width[, fillchar])

功能:返回右对齐的字符串,并使用 fillchar 填充至指定宽度。

案例:

text = "hello" result = text.rjust(10, "*") print(result) # 输出: "*****hello"

7.6 str.center(width[, fillchar])

功能:返回居中对齐的字符串,并使用 fillchar 填充至指定宽度。

案例:

text = "hello" result = text.center(11, "*") print(result) # 输出: "***hello***"

7.7 str.zfill(width)

功能:返回指定宽度的字符串,原字符串右对齐,前面填充 0。

案例:

text = "42" result = text.zfill(5) print(result) # 输出: "00042"

8. 字符串编码与解码

8.1 str.encode(encoding="utf-8", errors="strict")

功能:将字符串编码为 bytes 对象。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/18 3:28:36

学生作业高效完成指南:类型分析与应对策略

1. 第一次作业的常见类型与应对策略作为从业多年的教育工作者,我见过太多学生面对"第一次作业"时手足无措的样子。第一次作业通常分为以下几种典型类型:课程导入型:教授通过简单任务让学生熟悉教学平台和作业提交流程能力摸底型&am…

作者头像 李华
网站建设 2026/7/18 3:28:24

测试开发工程师必备网络命令实战指南

1. 测试开发工程师必备的网络命令手册作为在测试开发领域摸爬滚打多年的老鸟,我深刻体会到网络知识对测试工作的重要性。无论是接口测试、性能测试还是自动化测试,网络问题总是如影随形。记得刚入行时,因为不熟悉基本的网络排查命令&#xff…

作者头像 李华
网站建设 2026/7/18 3:28:08

桌面文件误删怎么办?这6款恢复工具,简单操作高效找回

在数字时代,电脑桌面是我们最常存放文件的地方,却也成为误操作的高发区。一不小心,重要文档、珍贵照片就可能被删除。调查显示,超过60%的用户曾因误删、系统故障或病毒攻击丢失过桌面文件,不仅影响工作,更可…

作者头像 李华
网站建设 2026/7/18 3:27:16

EasySpider:可视化无代码网页爬虫工具完全指南

一、项目简介 EasySpider(易采集)是一款完全免费、开源的可视化无代码网页爬虫工具,由开发者 NaiboWang 开发并维护。该项目在 GitHub 上已获得超过 44,000 颗星标,是目前最受欢迎的可视化爬虫软件之一。 EasySpider 采用图形化界…

作者头像 李华
网站建设 2026/7/18 3:27:09

Java 开发转型 AI Agent 开发第一课之认识 Agent!

介绍Agents Agents 将大语言模型(LLM)与工具(Tool)结合,创建具备:任务推理、工具使用决策、工具调用的自动化系统,系统具备持续推理、工具调用的循环迭代能力,直至问题解决。 Spring AI Alibaba 提供了基于的生产级 Agent 实现。 …

作者头像 李华
网站建设 2026/7/18 3:26:47

自动化测试浏览器连接失败:从版本匹配到系统环境的全面排查指南

1. 项目概述:当自动化测试工具“罢工”时做自动化测试的朋友,估计都遇到过这个让人血压飙升的场景:脚本写好了,环境配好了,信心满满地一运行,结果控制台给你弹出一行冰冷的错误——“无法连接到浏览器”或者…

作者头像 李华