学习目标全面掌握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 Worldprint(text.upper()) # 输出: HELLO WORLD2.2 lower() - 全小写将字符串中的所有字母转换为小写text Hello Worldprint(text.lower()) # 输出: hello world2.3 title() - 标题格式将每个单词的首字母大写text hello world pythonprint(text.title()) # 输出: Hello World Python2.4 capitalize() - 句首大写将字符串的第一个字符大写其余小写text hello WORLDprint(text.capitalize()) # 输出: Hello world2.5 swapcase() - 大小写互换大写变小写小写变大写text Hello Worldprint(text.swapcase()) # 输出: hELLO wORLD2.6 casefold() - 更激进的小写比lower()更激进用于忽略大小写的比较text HELLO WORLDprint(text.casefold()) # 输出: hello world# 特殊字符处理german Straße # 德语print(german.lower()) # straßeprint(german.casefold()) # strasse2.7 实战应用不区分大小写的比较user_input Yesif user_input.casefold() yes:print(用户同意) # 匹配Yes, YES, yes三、查找和替换方法3.1 find() - 查找子串查找子串第一次出现的位置找不到返回-1text Hello World, Hello Pythonprint(text.find(Hello)) # 输出: 0print(text.find(Python)) # 输出: 19print(text.find(Java)) # 输出: -1找不到3.2 index() - 查找子串报错版与find()类似但找不到会抛出ValueErrortext Hello Worldprint(text.index(Hello)) # 输出: 0# print(text.index(Java)) # 报错: ValueError3.3 rfind() 和 rindex() - 从右查找从字符串右边开始查找text Hello World, Hello Pythonprint(text.rfind(Hello)) # 输出: 13第二个Helloprint(text.rfind(o)) # 输出: 20最后一个o3.4 count() - 统计出现次数统计子串出现的次数text Hello World, Hello Pythonprint(text.count(Hello)) # 输出: 2print(text.count(l)) # 输出: 43.5 replace() - 替换子串替换子串为另一个子串text Hello World, Hello Pythonprint(text.replace(Hello, Hi)) # Hi World, Hi Pythonprint(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 texttext 这个坏蛋真是讨厌print(censor_text(text, [坏蛋])) # 这个***真是讨厌四、分割和连接方法4.1 split() - 分割字符串根据分隔符分割字符串返回列表text apple,banana,orangefruits text.split(,)print(fruits) # [apple, banana, orange]4.2 split() 限制分割次数data a,b,c,d,eprint(data.split(,, 2)) # [a, b, c,d,e]4.3 rsplit() - 从右分割从右边开始分割path /usr/local/bin/pythonprint(path.rsplit(/, 1)) # [/usr/local/bin, python]4.4 splitlines() - 按行分割按换行符分割字符串text Line1\nLine2\nLine3lines text.splitlines()print(lines) # [Line1, Line2, Line3]4.5 join() - 连接字符串使用指定字符串连接列表中的元素fruits [apple, banana, orange]print(-.join(fruits)) # apple-banana-orangeprint( .join(fruits)) # apple banana orangeprint().join(fruits)) # applebananaorange4.6 partition() 和 rpartition()将字符串分成三部分前、分隔符、后text Hello-World-Pythonprint(text.partition(-)) # (Hello, -, World-Python)print(text.rpartition(-)) # (Hello-World, -, Python)4.7 实战应用解析URLurl https://www.example.com/path/to/pageprotocol, sep, rest url.partition(://)print(protocol) # httpsdomain, sep, path rest.partition(/)print(domain) # www.example.comprint(path) # path/to/page五、去除空白字符方法5.1 strip() - 去除两端空白去除字符串开头和结尾的空白字符空格、制表符、换行符text Hello Worldprint(text.strip()) # Hello World5.2 lstrip() - 去除左边空白text Hello Worldprint(text.lstrip()) # Hello World 右边空格保留5.3 rstrip() - 去除右边空白text Hello Worldprint(text.rstrip()) # Hello World左边空格保留5.4 去除指定字符strip()方法可以指定要去除的字符text xxxHello Worldxxxprint(text.strip(x)) # Hello Worldtext 123Hello321print(text.strip(123)) # Hello去除1、2、35.5 实战应用清理用户输入def clean_input(user_input):# 去除两端空白并转为小写return user_input.strip().lower()email UserExample.COMclean_email clean_input(email)print(clean_email) # userexample.com六、判断验证方法6.1 startswith() - 检查开头检查字符串是否以指定子串开头text Hello Worldprint(text.startswith(Hello)) # Trueprint(text.startswith(Hi)) # False6.2 endswith() - 检查结尾检查字符串是否以指定子串结尾filename document.txtprint(filename.endswith(.txt)) # Trueprint(filename.endswith(.pdf)) # False6.3 isalpha() - 是否全是字母text Helloprint(text.isalpha()) # Truetext Hello123print(text.isalpha()) # False6.4 isdigit() - 是否全是数字text 12345print(text.isdigit()) # Truetext 12.34print(text.isdigit()) # False有小数点6.5 isalnum() - 是否字母或数字text Hello123print(text.isalnum()) # Truetext Hello 123print(text.isalnum()) # False有空格6.6 isspace() - 是否全是空白text print(text.isspace()) # True6.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 Helloprint(text.center(20)) # Helloprint(text.center(20, -)) # --------Hello--------7.2 ljust() - 左对齐字符串左对齐右侧填充text Helloprint(text.ljust(20, *)) # Hello***************7.3 rjust() - 右对齐字符串右对齐左侧填充text Helloprint(text.rjust(20, *)) # ***************Hello7.4 zfill() - 零填充在数字字符串左侧填充零num 42print(num.zfill(5)) # 00042print(num.zfill(10)) # 00000000427.5 expandtabs() - 制表符转空格将制表符\t转换为空格默认8个text Name\tAge\tCityprint(text.expandtabs()) # Name Age Cityprint(text.expandtabs(4)) # Name Age City7.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\xbdtext 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, encodingenc) as f:return f.read()except UnicodeDecodeError:continueraise ValueError(无法解码文件)九、高级字符串方法9.1 translate() 和 maketrans() - 字符转换创建翻译表并进行批量字符替换# 创建翻译表将a换成1b换成2c换成3table str.maketrans({a: 1, b: 2, c: 3})text abcdefprint(text.translate(table)) # 123def# 删除指定字符table str.maketrans(, , abc) # 第三个参数是要删除的text abcdefprint(text.translate(table)) # def9.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.txtprint(text.removeprefix(test_)) # file.txtprint(text.removesuffix(.txt)) # test_file9.4 removeprefix() 对比 lstrip()filename hello.txtprint(filename.removeprefix(hel)) # lo.txt精确匹配print(filename.lstrip(hel)) # o.txt删除所有h、e、l9.5 字符串格式化速查表格式示例输出% 格式化Hello %s % nameHello Aliceformat()Hello {}.format(name)Hello Alicef-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 1234def 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,Engineerdef 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], checksprint(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 language1. 将其转换为全大写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-learningparts text.split(-)print(parts) # [data, science, machine, learning]# 2. 用/连接result / .join(parts)print(result) # data/science/machine/learning# 3. 提取文件名和扩展名filename document.pdfname, dot, ext filename.partition(.)print(f文件名{name}) # 文件名documentprint(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 Falsereturn True# 测试print(validate_username(user_123)) # Trueprint(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:# 产品名左对齐宽度20name_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 redef clean_and_normalize_v2(text):# 去除两端空白并转为小写text text.strip().lower()# 将多个空格替换为单个空格text re.sub(r\s, , text)# 首字母大写text text.capitalize()return textprint(clean_and_normalize_v2(messy_text))十三、下篇预告第8篇《Python布尔类型与空值True、False和None》在下一篇中我们将学习- 布尔类型的概念和应用- 真值测试和布尔运算- None的含义和用法- 类型转换bool()函数- 布尔类型在条件判断中的应用敬请期待系列文章目录点击关注持续更新中...如果觉得有帮助请点赞 收藏 ⭐ 关注 ❤️你的支持是我持续创作的动力本文为本系列第7篇带你从零基础到Python实战