Python 字符串全套内置方法详解
·
前言
字符串是 Python 开发中使用频率最高的数据类型,文本处理、爬虫、文件读写、接口参数解析都离不开字符串操作。Python 内置了大量字符串处理方法,全部不会修改原字符串,只会返回新字符串。 本文整合所有高频字符串方法,分类讲解并配套可直接运行的代码示例,适合新手收藏复习。
一、查找类方法:find /index/count
用于查找子字符串位置、统计出现次数,支持设置查找区间[start, end]。
find(sub, start, end):查找子串下标,找不到返回-1;rfind()从字符串右侧反向查找index(sub, start, end):查找子串下标,找不到直接抛出异常;rindex()从右侧查找count(sub, start, end):统计子串出现次数,无匹配返回 0
# find/rfind
print("hello world".find("llo")) # 2
print("hello world".find("ll0")) # -1 不存在返回-1
print("hello world".rfind("l")) # 9
# index/rindex
print("hello world".index("llo")) # 2
# print("hello world".index("ll0")) # 不存在直接报错
# count统计次数
print("hello world".count("l")) # 3
print("hello world".count("l", 4))# 从下标4开始统计
二、大小写转换方法
统一修改字符串大小写,返回全新字符串:
lower():全部转为小写upper():全部转为大写capitalize():仅字符串首字母大写,其余小写title():每个独立单词首字母大写swapcase():大小写互相翻转
s = "heLlo WorlD"
print(s.lower()) # hello world
print(s.upper()) # HELLO WORLD
print(s.capitalize()) # Hello world
print(s.title()) # Hello World
print(s.swapcase()) # HElLO wORLd
三、字符串对齐与填充
固定字符串长度,实现居中、左对齐、右对齐、数字补 0 场景:
center(width, fillchar):居中,不足长度用指定字符填充(默认空格)ljust(width, fillchar):左对齐,右侧填充字符rjust(width, fillchar):右对齐,左侧填充字符zfill(width):右对齐,左侧自动填充 0,常用于数字格式化
text = "hello world"
print(text.center(20, "*")) # ****hello world****
print(text.ljust(20, "*")) # hello world********
print(text.rjust(20, "*")) # ********hello world
print(text.zfill(20)) # 00000000hello world
四、首尾内容判断:startswith /endswith
判断字符串是否以指定字符 / 子串开头、结尾,返回布尔值True/False。
s = " hello world "
print(s.startswith(" ")) # True
print(s.endswith(" ")) # True
print(s.startswith("hello")) # False
五、剔除首尾字符:strip /lstrip/rstrip
默认清除首尾空白(空格、\n、\t),可自定义需要剔除的符号:
strip():左右两端同时剔除lstrip():仅剔除左侧字符rstrip():仅剔除右侧字符
s = "+++hello world+++"
print(s.strip("+")) # hello world
print(s.lstrip("+")) # hello world+++
print(s.rstrip("+")) # +++hello world
六、切割、拼接、替换 split /join/replace
1. split () 字符串切割
按指定分隔符拆分字符串,返回列表;不传参数默认按所有空白切割。
print("hello world".split()) # ['hello', 'world']
print("hello world".split('l')) # ['he', '', 'o wor', 'd']
2. join () 序列拼接
以当前字符串作为分隔符,拼接列表、元组等可迭代对象为完整字符串。
print(" ".join(['hello', 'world'])) # hello world
print("++".join("hi")) # h++i
3. replace () 内容替换
替换指定子串,可选参数count限制最大替换次数。
str1 = "hello world hello china"
# 只替换第一个hello
print(str1.replace("hello", "hi", 1)) # hi world hello china
七、编码与解码 encode /decode
字符串与字节流 bytes 互相转换,常用于文件读写、网络传输:
字符串.encode(编码格式):字符串 → bytes 字节流(支持 utf8、gbk 等)字节串.decode(编码格式):bytes 字节流 → 普通字符串
# 编码
byte_data = "hello world 123 中国".encode("gbk")
print(byte_data)
# 解码
res = b'hello world 123 \xd6\xd0\xb9\xfa'.decode("gbk")
print(res) # hello world 123 中国
八、is 系列判断方法(返回布尔值)
批量判断字符串组成格式,做数据校验常用:
isalpha():字符串全部由字母组成isdigit():字符串全部由纯数字组成isalnum():仅包含字母 + 数字,无特殊符号islower():所有英文字母全小写isupper():所有英文字母全大写istitle():每个单词首字母大写,其余小写
print("az".isalpha()) # True
print("19".isdigit()) # True
print("19az".isalnum()) # True
print("Az".islower()) # False
print("AZ".isupper()) # True
print("Az Bz".istitle()) # True
更多推荐


所有评论(0)