Python 字符串内置方法全分类详解
一、判断类方法(返回 True/False,isxxx)
1. str.isdigit()
判断字符串全部由纯数字0-9组成,不能有小数点、负号、空格
print("123".isdigit()) # True
print("12.3".isdigit()) # False
print("-123".isdigit()) # False
print("12a3".isdigit()) # False
2. str.isnumeric()
包含汉字数字、罗马数字、全角数字,范围比isdigit更大
print("123".isnumeric()) # True
print("一二三".isnumeric()) # True
3. str.isdecimal()
仅十进制数字,不识别罗马/中文数字
print("123".isdecimal()) # True
print("一二三".isdecimal()) # False
4. str.isalpha()
全部是字母(中英文),无数字、符号、空格
print("abc中文".isalpha()) # True
print("abc123".isalpha()) # False
5. str.isalnum()
字母+数字混合均可,不含符号空格
print("abc123".isalnum()) # True
print("abc_123".isalnum())# False
6. str.islower() / str.isupper()
是否全小写 / 全大写(必须有字母,纯数字返回False)
print("hello".islower()) # True
print("HELLO".isupper()) # True
print("123".islower()) # False
7. str.istitle()
每个单词首字母大写,其余小写
print("Hello World".istitle()) # True
print("hello World".istitle()) # False
8. str.isspace()
字符串只有空白字符(空格、\t \n \r)
print(" \t".isspace()) # True
print(" a ".isspace()) # False
9. str.isprintable()
所有字符均可打印(不含转义控制字符)
二、查找、分割、分区类(find/index/split/partition)
1. str.find(sub, start=0, end=None)
查找子串,返回第一次出现下标;找不到返回 -1(不报错)
s = "abcabc"
print(s.find("ab")) # 0
print(s.find("ab", 2)) # 3
print(s.find("xyz")) # -1
2. str.rfind()
从右往左查找,返回最后一次出现下标
print("abcabc".rfind("ab")) # 3
3. str.index(sub)
和find一样,但是找不到直接抛 ValueError
"abc".index("x") # 报错
rindex() 从右找,同样找不到报错
4. str.count(sub, start, end)
统计子串出现次数
"ababa".count("aba") # 2
5. str.partition(sep)
分成三部分元组 (前面,分隔符,后面),只分割第一次出现的sep
格式:(head, sep, tail)
s = "name=zhangsan"
print(s.partition("="))
# ('name', '=', 'zhangsan')
# 找不到分隔符
print("hello".partition("="))
# ('hello', '', '')
6. str.rpartition(sep)
从右边分割,只分割最后一个分隔符
"a=b=c".rpartition("=") # ('a=b', '=', 'c')
7. str.split(sep=None, maxsplit=-1)
按分隔符切割,返回列表;maxsplit 指定最多分割几次
- sep=None:自动按任意空白分割,自动忽略首尾空格
print("a,b,c".split(",")) # ['a','b','c']
print("1 2 3".split()) # ['1','2','3']
print("a|b|c".split("|",1)) # ['a','b|c']
8. str.rsplit()
从右开始分割
"a b c".rsplit(" ",1) # ['a b', 'c']
9. str.splitlines(keepends=False)
按换行符 \n \r \r\n 分割多行字符串
"a\nb\nc".splitlines() # ['a','b','c']
10. str.startswith(prefix) / str.endswith(suffix)
判断是否以指定串开头/结尾,支持元组多匹配
"test.py".endswith((".py", ".txt")) # True
"hello".startswith("he") # True
三、替换、修剪、填充类
1. str.replace(old, new, count=-1)
替换子串,count指定替换前N个
"aaaa".replace("a","b",2) # 'bbaa'
2. strip() / lstrip() / rstrip()
去除首尾空白/指定字符
s = " abc "
print(s.strip()) # "abc" 去除左右空格
print(s.lstrip()) # "abc " 只去左边
print(s.rstrip()) # " abc" 只去右边
print(",,abc,".strip(",")) # 'abc'
3. 对齐填充:ljust / rjust / center
# 总长度5,不足用*填充
print("hi".ljust(5,"*")) # hi*** 左对齐
print("hi".rjust(5,"*")) # ***hi 右对齐
print("hi".center(5,"*")) # *hi* 居中
4. zfill(width) 数字补0
print("123".zfill(5)) # 00123
print("-45".zfill(4)) # -045
四、大小写转换
str.lower()全部小写str.upper()全部大写str.title()每个单词首字母大写str.capitalize()首字母大写,其余小写str.swapcase()大小写互换
s = "hello WORLD"
print(s.lower()) # hello world
print(s.upper()) # HELLO WORLD
print(s.title()) # Hello World
print(s.capitalize()) # Hello world
print(s.swapcase()) # HELLO world
五、编码、拼接、格式化
1. str.join(iterable)
分隔符拼接可迭代对象(前文讲过)
",".join(["1","2","3"]) # '1,2,3'
2. str.encode(encoding="utf-8") 字符串转字节
"中文".encode("utf-8") # b'\xe4\xb8\xad\xe6\x96\x87'
反向:bytes.decode()
3. str.format() / f-string替代方案
"name:{},age:{}".format("Tom",18)
4. str.format_map(dict) 字典格式化
"name:{name}".format_map({"name":"Jack"})
六、其他实用方法
1. str.maketrans() + str.translate() 批量字符替换
table = str.maketrans({"a":"1", "b":"2"})
print("abx".translate(table)) # 12x
2. expandtabs(tabsize=8) 把\t转为空格
"a\tb".expandtabs(4) # a b
3. removeprefix() / removesuffix() (Python3.9+)
安全删除开头/结尾固定字符串,不存在则原样返回
"test.py".removesuffix(".py") # test
"abc".removeprefix("x") # abc
快速记忆分类
- 判断isXXX:返回布尔,校验数字、字母、大小写、空白
- 查找find/index/count:定位子串位置
- 分割split/partition:拆分字符串,partition固定三段式
- 修剪strip、对齐填充ljust/zfill:处理首尾和长度
- 大小写转换 lower/upper/title
- 替换replace、translate
- 拼接join、编码encode、分割splitlines