一、索引分类
按用途索引
函数 | 简述 |
---|---|
字符串转换 | |
大小写转换 | |
str.capitalize() | 首字母大写,其余小写 |
str.casefold() | 大写转换为小写 |
str.lower() | 大写转换为小写(只对 ASCII 码有效,也就是 'A-Z’有效) |
str.upper() | 小写转换为大写 |
str.swapcase() | 大写转换为小写,小写转换为大写 |
其他 | |
str.replace(old, new[, count]) | 字符串中str的子字符串old被被替换为 new |
str.expandtabs([tabsize=8]) | 制表符转换为空格符 |
str.title() | 转换为标题的形式 |
str.format(*args, **kwargs) | 字符串str的格式化操作 |
str.format_map(mapping) | 字符串str的格式化操作,类似于str.format(*args, **kwargs) |
str.encode(encoding=“utf-8”[, errors=“strict”]) | 转换为 encoding 指定的字符编码串 |
字符串处理 | |
字符填充 | |
str.center(width[, fillchar]) | 原字符串在中间,填补字符分散在两边 |
str.ljust(width[, fillchar]) | 原字符串靠左对齐,填补字符在原字符串右边 |
str.rjust(width[, fillchar]) | 原字符串靠右对齐,填补字符在原字符串左边 |
str.zfill(width) | 用ASCII码中的数字 ‘0’ 在原字符串左边填充,并扩充为width的长度 |
字符串连接与分割 | |
str.join(iterable) | 多个字符串以 str 为间隔符连接在一起 |
str.partition(sep) | 将字符串以 sep 为间隔符,且在sep第一次出现的位置分割成两部分,并返回3个元素的元组 |
str.rpartition(sep) | 将字符串以 sep 为间隔符,且在sep最后一次出现的位置分割成两部分,并返回3个元素的元组 |
str.rsplit(sep=None, maxsplit=-1) | 从右向左以 sep 为间隔符分割maxsplit指定的次数,并返回maxsplit+1个元素的列表 |
str.split(sep=None, maxsplit=-1) | 从左向右以 sep 为间隔符分割maxsplit指定的次数,并返回maxsplit+1个元素的列表 |
str.splitlines([keepends]) | 字符串以行边界符为间隔符进行分割,并返回一个列表 |
去除前后缀 | |
str.lstrip([chars]) | 按照 chars 的任意组合,去除字符串 str 的前缀 |
str.rstrip([chars]) | 按照 chars 的任意组合,去除字符串 str 的后缀 |
str.strip([chars]) | 按照 chars 的任意组合,去除字符串 str 的前缀与后缀 |
字符映射 | |
str.translate(table) | 字符串中的字符按给定的转换表进行映射,可以使用 str.maketrans() 创建字符映射转换表。 |
static str.maketrans(x[, y[, z]]) | 静态方法,返回一个可供 str.translate() 使用的转换对照表 |
查找 | |
str.count(sub[, start[, end]]) | 子字符串 sub 重复出现的次数 |
str.find(sub[, start[, end]]) | 子字符串 sub 的最小索引,找不到返回 -1 |
str.rfind(sub[, start[, end]]) | 子字符串 sub 的最大索引,找不到返回 -1 |
str.index(sub[, start[, end]]) | 子字符串 sub 的最小索引,找不到会报错 |
str.rindex(sub[, start[, end]]) | 子字符串 sub 的最大索引,找不到会报错 |
判断字符串 | |
数字与字母 | |
str.isalnum() | 均为字母或数字,返回True,否则返回False |
str.isalpha() | 均为字母,返回True,否则返回False |
str.islower() | 均为小写字母,返回True,否则返回False |
str.isupper() | 均为大写字母,返回True,否则返回False |
str.isdecimal() | 均为数字字符(不包含Byte数字字符,仅包含十进制数字字符),返回True,否则返回False |
str.isdigit() | 均为数字字符(包含Byte数字字符),返回True,否则返回False |
str.isnumeric() | 均为数字字符(不包含Byte数字字符,包含中文数字字符和罗马数字字符),返回True,否则返回False |
其他 | |
str.isspace() | 均为空白字符,且不是空字符串,返回True,否则返回False |
str.isascii() | 均为ASCII字符或为空字符串,返回True,否则返回False |
str.endswith(suffix[, start[, end]]) | 判断字符串是否以 suffix 子字符串作为后缀 |
str.startswith(prefix[, start[, end]]) | 判断字符串是否以 prefix 子字符串作为前缀 |
str.isidentifier() | 是合法的标识符或关键字,返回True,否则返回False |
str.isprintable() | 均为可打印字符或字符串为空,返回True,否则返回False |
str.istitle() | 是标题字符串(单词的首字母大写其他小写),返回True,否则返回False。 |
按名称索引
函数 | 简述 |
---|---|
C | |
str.capitalize() | 首字母大写,其余小写 |
str.casefold() | 大写转换为小写 |
str.center(width[, fillchar]) | 原字符串在中间,填补字符分散在两边 |
str.count(sub[, start[, end]]) | 子字符串 sub 重复出现的次数 |
E | |
str.encode(encoding=“utf-8”[, errors=“strict”]) | 转换为 encoding 指定的字符编码串 |
str.endswith(suffix[, start[, end]]) | 判断字符串是否以 suffix 子字符串作为后缀 |
str.expandtabs([tabsize=8]) | 制表符转换为空格符 |
F | |
str.find(sub[, start[, end]]) | 子字符串 sub 的最小索引,找不到返回 -1 |
str.format(*args, **kwargs) | 字符串str的格式化操作 |
str.format_map(mapping) | 字符串str的格式化操作,类似于str.format(*args, **kwargs) |
I | |
str.index(sub[, start[, end]]) | 子字符串 sub 的最小索引,找不到会报错 |
str.isalnum() | 均为字母或数字,返回True,否则返回False |
str.isalpha() | 均为字母,返回True,否则返回False |
str.isascii() | 均为ASCII字符或为空字符串,返回True,否则返回Falsestr.isdecimal() |
str.isdigit() | 均为数字字符(包含Byte数字字符),返回True,否则返回False |
str.isidentifier() | 是合法的标识符或关键字,返回True,否则返回False |
str.islower() | 均为小写字母,返回True,否则返回False |
str.isnumeric() | 均为数字字符(不包含Byte数字字符,包含中文数字字符和罗马数字字符),返回True,否则返回False |
str.isprintable() | 均为可打印字符或字符串为空,返回True,否则返回False |
str.isspace() | 均为空白字符,且不是空字符串,返回True,否则返回False |
str.istitle() | 是标题字符串(单词的首字母大写其他小写),返回True,否则返回False。 |
str.isupper() | 均为大写字母,返回True,否则返回False |
J | |
str.join(iterable) | 多个字符串以 str 为间隔符连接在一起 |
L | |
str.ljust(width[, fillchar]) | 原字符串靠左对齐,填补字符在原字符串右边 |
str.lower() | 大写转换为小写(只对 ASCII 码有效,也就是 'A-Z’有效) |
str.lstrip([chars]) | 按照 chars 的任意组合,去除字符串 str 的前缀 |
M | |
static str.maketrans(x[, y[, z]]) | 静态方法,返回一个可供 str.translate() 使用的转换对照表 |
P | |
str.partition(sep) | 将字符串以 sep 为间隔符,且在sep第一次出现的位置分割成两部分,并返回3个元素的元组 |
R | |
str.replace(old, new[, count]) | 字符串中str的子字符串old被被替换为 new |
str.rfind(sub[, start[, end]]) | 子字符串 sub 的最大索引,找不到返回 -1 |
str.rindex(sub[, start[, end]]) | 子字符串 sub 的最大索引,找不到会报错 |
str.rjust(width[, fillchar]) | 原字符串靠右对齐,填补字符在原字符串左边 |
str.rpartition(sep) | 将字符串以 sep 为间隔符,且在sep最后一次出现的位置分割成两部分,并返回3个元素的元组 |
str.rsplit(sep=None, maxsplit=-1) | 从右向左以 sep 为间隔符分割maxsplit指定的次数,并返回maxsplit+1个元素的列表 |
str.rstrip([chars]) | 按照 chars 的任意组合,去除字符串 str 的后缀 |
S | |
str.split(sep=None, maxsplit=-1) | 从左向右以 sep 为间隔符分割maxsplit指定的次数,并返回maxsplit+1个元素的列表 |
str.splitlines([keepends]) | 字符串以边界符为间隔符进行分割,并返回一个列表 |
str.startswith(prefix[, start[, end]]) | 判断字符串是否以 prefix 子字符串作为前缀 |
str.strip([chars]) | 按照 chars 的任意组合,去除字符串 str 的前缀与后缀 |
str.swapcase() | 大写转换为小写,小写转换为大写 |
str.title() | 转换为标题的形式 |
str.translate(table) | 字符串中的字符按给定的转换表进行映射,可以使用 str.maketrans() 创建字符映射转换表。 |
str.upper() | 小写转换为大写 |
str.zfill(width) | 用ASCII码中的数字 ‘0’ 在原字符串左边填充,并扩充为width的长度 |
二、函数说明
str.capitalize()
说明:将字符串的首字母转换为大写,其余转换为小写。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.capitalize() 部分。实例如下所示:
print("hello world! hi".capitalize())
print("HELLO WORLD! HI".capitalize())
'''-------------------↓打印内容↓------------------------
Hello world! hi
Hello world! hi
----------------------↑打印内容↑---------------------'''
str.casefold()
说明:将字符串中所有字符的大写转换为小写。结果为新的字符串对象。Python 3.3 版本的新功能
更详细说明请参阅 Python官方文档>str.casefold() 部分。实例如下所示:
print("Hello world! Hi".casefold())
print("HELLO WORLD! HI".casefold())
print("ß".casefold()) # 德语中'ß'的小写是'ss'
'''-------------------↓打印内容↓------------------------
hello world! hi
hello world! hi
ss
----------------------↑打印内容↑---------------------'''
str.center(width[, fillchar])
说明:用fillchar指定的单一字符将原字符串扩充为width的长度,原字符串在中间,填补字符分散在两边。如果width小于原字符长度则不做扩充,不指定fillchar则默认用空格字符填补。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.center() 部分。实例如下所示:
print("ab".center(6, '#'))
print("ab".center(5, "*"))
print("abc".center(5, "@"))
print("abc".center(6, "$"))
'''-------------------↓打印内容↓------------------------
##ab##
**ab*
@abc@
$abc$$
----------------------↑打印内容↑---------------------'''
str.count(sub[, start[, end]])
说明:在 str[start:end] 切片中子字符串 sub 重复出现的次数。
更详细说明请参阅 Python官方文档>str.center() 部分。实例如下所示:
print("hello".count('l'))
print("hello".count('ll'))
print("ttabttta bttabab".count('ab'))
print("ababab".count('ba'))
'''-------------------↓打印内容↓------------------------
2
1
3
2
----------------------↑打印内容↑---------------------'''
str.encode(encoding="utf-8"[, errors="strict"])
说明:将字符串转换为 encoding 指定的字符编码串。encoding默认值为utf-8;errors默认值strict(表示编码错误会引发 UnicodeError),用来指定不同的错误处理方案。
更详细说明请参阅 Python官方文档>str.encode() 部分。实例如下所示:
print("你好,hello".encode())
print("你好,hello".encode(encoding="GBK"))
'''-------------------↓打印内容↓------------------------
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8chello'
b'\xc4\xe3\xba\xc3\xa3\xachello'
----------------------↑打印内容↑---------------------'''
str.endswith(suffix[, start[, end]])
说明:判断字符串 str[start:end] 的末尾是否以suffix子字符串作为后缀结束的。suffix可以是由多个子字符串组成的元组。
更详细说明请参阅 Python官方文档>str.endswith() 部分。实例如下所示:
print("你好,hello".endswith("hello"))
print("你好,hello".endswith("helo"))
print("你好,hello".endswith(("aa", "world", "hello")))
'''-------------------↓打印内容↓------------------------
True
False
True
----------------------↑打印内容↑---------------------'''
str.expandtabs([tabsize=8])
说明:将字符串中的制表符转换为同等宽度的空格符,制表符总的宽度由tabsize指定,默认是8,表示8个字符为一个制表位。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.expandtabs() 部分。实例如下所示:
print("0123456789")
print("a\tbc")
print("a\tbc".expandtabs())
print("a\tbc".expandtabs(tabsize=8))
print("a\tbc".expandtabs(tabsize=3))
print("ab\tc".expandtabs(tabsize=3))
'''-------------------↓打印内容↓------------------------
0123456789
a bc
a bc
a bc
a bc
ab c
----------------------↑打印内容↑---------------------'''
str.find(sub[, start[, end]])
说明:字符串 str[start:end] 切片中子字符串 sub 的最小索引。 如果 sub 未被找到则返回 -1。如果判断sub是否存在于切片内,请使用 in 运算符。
更详细说明请参阅 Python官方文档>str.find() 部分。实例如下所示:
print("Hello Hello".find("lo"))
print("Hello Hello".find("lo", 4))
print("Hello Hello".find("lo", 4, 10))
print("Hello Hello".find("lo", 4, 11))
'''-------------------↓打印内容↓------------------------
3
9
-1
9
----------------------↑打印内容↑---------------------'''
str.format(*args, **kwargs)
说明:字符串str的格式化操作。 字符串str由字符串字面值或以花括号 {} 括起来的替换域组成。 每个替换域可以包含一个位置参数的数字索引,或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替换为对应参数的字符串值。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.format() 部分。实例如下所示:
print("Hello {0}, {1}, {0}, {name1}".format("AAA", "bbb", name1="CCC"))
'''-------------------↓打印内容↓------------------------
Hello AAA, bbb, AAA, CCC
----------------------↑打印内容↑---------------------'''
str.format_map(mapping)
说明:效果类似于 str.format(*args, **kwargs) ,Python 3.2 版本的新功能。更详细说明请参阅 Python官方文档>str.format_map() 部分。
str.index(sub[, start[, end]])
说明:字符串 str[start:end] 切片中子字符串 sub 的最小索引。 类似于str.find(sub[, start[, end]]),但如果 sub 未被找到则会引发错误,而不是返回-1。
更详细说明请参阅 Python官方文档>str.index() 部分。实例如下所示:
print("Hello Hello".index("lo"))
print("Hello Hello".index("lo", 4))
print("Hello Hello".index("lo", 4, 10))
'''-------------------↓打印内容↓------------------------
3
9
ValueError: substring not found
----------------------↑打印内容↑---------------------'''
str.isalnum()
说明:字符串 str 均为字母或数字,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isalnum() 部分。实例如下所示:
print("Hello world".isalnum())
print("HelloWorld#".isalnum())
print("HelloWorld".isalnum())
print("Hello12345".isalnum())
print("0123456789".isalnum())
'''-------------------↓打印内容↓------------------------
False
False
True
True
True
----------------------↑打印内容↑---------------------'''
str.isalpha()
说明:字符串 str 均为字母,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isalpha() 部分。实例如下所示:
print("Hello world".isalpha())
print("HelloWorld#".isalpha())
print("HelloWorld".isalpha())
print("Hello12345".isalpha())
print("0123456789".isalpha())
'''-------------------↓打印内容↓------------------------
False
False
True
False
False
----------------------↑打印内容↑---------------------'''
str.isascii()
说明:字符串 str 均为ASCII字符,或为空字符串,返回真值True,否则返回假值False。Python 3.7版本的新功能。
更详细说明请参阅 Python官方文档>str.isascii() 部分。实例如下所示:
print("Hello world".isascii())
print("HelloWorld#".isascii())
print("HelloWorld".isascii())
print("Hello12345".isascii())
print("0123456789".isascii())
print("".isascii())
'''-------------------↓打印内容↓------------------------
True
True
True
True
True
True
----------------------↑打印内容↑---------------------'''
str.isdecimal()
说明:字符串 str 均为十进制数字字符(不包含Byte数字字符,仅包含十进制数字字符),返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isdecimal() 部分。实例如下所示:
print("789".isdecimal()) # Unicode 数字字符(半角数字),真值
print("7.89".isdecimal()) # Unicode 小数数字字符(半角数字),假值
print("789".isdecimal()) # 全角数字字符,真值
print("ⅦⅧⅨ".isdecimal()) # 罗马数字字符,假值
print("七八九".isdecimal()) # 中文小写数字字符,假值
print("柒捌玖".isdecimal()) # 中文大写数字字符,假值
print(b'7'.isdecimal()) # byte数字,报错
'''-------------------↓打印内容↓------------------------
True
False
True
False
False
False
AttributeError: 'bytes' object has no attribute 'isdecimal'
----------------------↑打印内容↑---------------------'''
str.isdigit()
说明:字符串 str 均为数字(包含Byte数字字符),返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isdigit() 部分。实例如下所示:
print("789".isdigit()) # Unicode 数字字符(半角数字),真值
print("7.89".isdigit()) # Unicode 小数数字字符(半角数字),假值
print("789".isdigit()) # 全角数字字符,真值
print("ⅦⅧⅨ".isdigit()) # 罗马数字字符,假值
print("七八九".isdigit()) # 中文小写数字字符,假值
print("柒捌玖".isdigit()) # 中文大写数字字符,假值
print(b'7'.isdigit()) # byte数字,真值
'''-------------------↓打印内容↓------------------------
True
False
True
False
False
False
True
----------------------↑打印内容↑---------------------'''
str.isidentifier()
说明:字符串 str 是合法的标识符或关键字(满足标识符的命名规则),返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isidentifier() 部分。实例如下所示:
print("if".isidentifier())
print("def".isidentifier())
print("aa12".isidentifier())
print("_aa12".isidentifier())
print("12_aa".isidentifier())
print("12&aa".isidentifier())
print("".isidentifier())
'''-------------------↓打印内容↓------------------------
True
True
True
True
False
False
False
----------------------↑打印内容↑---------------------'''
str.islower()
说明:字符串 str 均为小写字符,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.islower() 部分。实例如下所示:
print("abc".islower())
print("abC".islower())
'''-------------------↓打印内容↓------------------------
True
False
----------------------↑打印内容↑---------------------'''
str.isnumeric()
说明:字符串 str 均为数字(不包含Byte数字字符,包含中文数字字符和罗马数字字符),返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isnumeric() 部分。实例如下所示:
print("789".isnumeric()) # Unicode 数字字符(半角数字)
print("7.89".isnumeric()) # Unicode 小数数字字符(半角数字)
print("789".isnumeric()) # 全角数字字符
print("ⅦⅧⅨ".isnumeric()) # 罗马数字字符
print("七八九".isnumeric()) # 中文小写数字字符
print("柒捌玖".isnumeric()) # 中文大写数字字符
print(b'7'.isnumeric()) # byte数字
'''-------------------↓打印内容↓------------------------
True
False
True
True
True
True
AttributeError: 'bytes' object has no attribute 'isnumeric'
----------------------↑打印内容↑---------------------'''
str.isprintable()
说明:字符串 str 均为可打印字符或字符串为空,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isprintable() 部分。实例如下所示:
print("a".isprintable())
print("$".isprintable())
print("".isprintable())
print(" ".isprintable()) # 空格符
print("\40".isprintable()) # 空格符,即十进制的32,同上
print("\t".isprintable()) # 控制字符-制表符
print("\r".isprintable()) # 控制字符-回车符
print("\n".isprintable()) # 控制字符-换行符
print("\7".isprintable()) # 控制字符-响铃(BEL)
'''-------------------↓打印内容↓------------------------
True
True
True
True
True
False
False
False
False
----------------------↑打印内容↑---------------------'''
str.isspace()
说明:字符串 str 均为空白字符,且不是空字符串,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isspace() 部分。实例如下所示:
print("a".isspace())
print("".isspace()) # 空字符串
print(" ".isspace()) # 空格符
print("\40".isspace()) # 空格符,即十进制的32,同上
print("\t".isspace()) # 控制字符-制表符
print("\r".isspace()) # 控制字符-回车符
print("\n".isspace()) # 控制字符-换行符
'''-------------------↓打印内容↓------------------------
False
False
True
True
True
True
True
----------------------↑打印内容↑---------------------'''
str.istitle()
说明:字符串 str 是有标题的字符串,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.istitle() 部分。实例如下所示:
print("hello".istitle())
print("Hello".istitle())
print("HEllo".istitle())
print("Hello world".istitle())
print("Hello World".istitle())
print("Hello World".istitle())
print("标题一".istitle())
'''-------------------↓打印内容↓------------------------
False
True
False
False
True
True
False
----------------------↑打印内容↑---------------------'''
str.isupper()
说明:字符串 str 均为小写字符,返回真值True,否则返回假值False。
更详细说明请参阅 Python官方文档>str.isupper() 部分。实例如下所示:
print("ABC".isupper())
print("aBC".isupper())
'''-------------------↓打印内容↓------------------------
True
False
----------------------↑打印内容↑---------------------'''
str.join(iterable)
说明:将 iterable 中的多个字符串以 str 为间隔符连接在一起,成为一个新的字符串。
更详细说明请参阅 Python官方文档>str.() 部分。实例如下所示:
print("-".join("abcde"))
print("-".join(('a', 'b', 'c')))
print("-".join(['a', 'b', 'c']))
print("-".join(('a')))
print("-".join('a'))
'''-------------------↓打印内容↓------------------------
a-b-c-d-e
a-b-c
a-b-c
a
a
----------------------↑打印内容↑---------------------'''
str.ljust(width[, fillchar])
说明:用fillchar指定的单一字符*将原字符串扩充为width的长度,原字符串靠左对齐,填补字符在原字符串右边。 如果width小于原字符长度则不做扩充,不指定fillchar则默认用空格字符填补。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.ljust() 部分。实例如下所示:
print("ab".ljust(6, '#'))
print("ab".ljust(5, "*"))
print("abc".ljust(5, "@"))
print("abc".ljust(6, "$"))
'''-------------------↓打印内容↓------------------------
ab####
ab***
abc@@
abc$$$
----------------------↑打印内容↑---------------------'''
str.lower()
说明:将字符串中所有字符的大写转换为小写(只对 ASCII 码有效,也就是 'A-Z’有效)。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.lower() 部分。实例如下所示:
print("Hello world! Hi".lower())
print("HELLO WORLD! HI".lower())
print("ß".lower()) # 德语中'ß'的小写是'ss',但lower只能对英文 'A-Z' 有效
'''-------------------↓打印内容↓------------------------
hello world! hi
hello world! hi
ß
----------------------↑打印内容↑---------------------'''
str.lstrip([chars])
说明:按照 chars 指定的字符串的任意组合,去除字符串 str 的前缀。如果不指定chars或为None则去除空格。
更详细说明请参阅 Python官方文档>str.lstrip() 部分。实例如下所示:
print('hello world'.lstrip('leoh')) # leoh 可以组合为 hello,所以去掉前缀hello
print('hello world'.lstrip('**l@@e$$o&&h##')) # **l@@e$$o&&h## 可以组合为 hello,所以去掉前缀hello
print('hello world'.lstrip('leo')) # leh 的所有组合都不是字符串的前缀,所以不会有前缀被去掉
print('hello world'.lstrip('elo')) # elo 的所有组合都不是字符串的前缀,所以不会有前缀被去掉
print(' llo world'.lstrip()) # 不指定参数则去除空格前缀
print(' llo world'.lstrip(None)) # 参数为None则去除空格前缀
print('hello world'.lstrip()) # 不指定参数则去除空格前缀,但并没有空格前缀,所以不会有前缀被去掉
print('hello world'.lstrip(None)) # 参数为None则去除空格前缀,但并没有空格前缀,所以不会有前缀被去掉
'''-------------------↓打印内容↓------------------------
world
world
hello world
hello world
llo world
llo world
hello world
hello world
----------------------↑打印内容↑---------------------'''
static str.maketrans(x[, y[, z]])
说明:静态方法,返回一个可供 str.translate() 使用的转换对照表。只有一个参数时必须是字典类型或字典类型None,键值对中的键必须是一个字符的字符串;如果两个参数 x,y 长度必须是相等的字符串,x中每个字符将映射到y中相同位置的字符;如果三个参数,第三个参数必须是个字符串,其字符将被映射为None。
更详细说明请参阅 Python官方文档>str.maketrans() 部分。实例如下所示:
x = "ace"
y = "123"
z = "b"
dicX = {'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 's': '6'}
str0 = str.maketrans(dicX) # 创建字符映射转换表
print("abcde".translate(str0))
dicX = {'a': '1', 'b': None, 'c': '3', 'd': '4', 'e': '5', 's': '6'}
str0 = str.maketrans(dicX) # 创建字符映射转换表
str1 = str.maketrans(x, y) # 创建字符映射转换表
str2 = str.maketrans(x, y, z) # 创建字符映射转换表,并删除指定字符
print("abcde".translate(str0))
print("abcde".translate(str1))
print("abcde".translate(str2))
'''-------------------↓打印内容↓------------------------
12345
1345
1b2d3
12d3
----------------------↑打印内容↑---------------------'''
str.partition(sep)
说明:将字符串 str 以 sep 为间隔符且在 sep 第一次出现的位置分割成两部分,并返回3个元素的元组。其中包含分隔符之前的部分字符串、分隔符本身,以及分隔符之后的部分字符串。 如果分隔符未找到,则返回的元组中包含字符本身以及两个空字符串。sep 不允许为空字符串。
更详细说明请参阅 Python官方文档>str.partition() 部分。实例如下所示:
print("a-b-c".partition('-'))
print("abcde".partition('c'))
print("abcde".partition('bcd'))
print("abcde".partition('bcc'))
'''-------------------↓打印内容↓------------------------
('a', '-', 'b-c')
('ab', 'c', 'de')
('a', 'bcd', 'e')
('abcde', '', '')
----------------------↑打印内容↑---------------------'''
str.replace(old, new[, count])
说明:字符串str中 的 子字符串 old 被被替换为 new。 如果给出了可选参数 count,则只替换前 count 次。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.replace() 部分。实例如下所示:
print("a-b-c-d-e".replace('-', '+'))
print("a-b-c-d-e".replace('-', '+', 2))
'''-------------------↓打印内容↓------------------------
a+b+c+d+e
a+b+c-d-e
----------------------↑打印内容↑---------------------'''
str.rfind(sub[, start[, end]])
说明:字符串 str[start:end] 切片中子字符串 sub 的最大索引。 如果 sub 未被找到则返回 -1。如果判断sub是否存在于切片内,请使用 in 运算符。
更详细说明请参阅 Python官方文档>str.rfind() 部分。实例如下所示:
print("Hello Hello".rfind("lo"))
print("Hello Hello".rfind("lo", 1))
print("Hello Hello".rfind("lo", 1, 6))
print("Hello Hello".rfind("lo", 1, 3))
'''-------------------↓打印内容↓------------------------
9
9
3
-1
----------------------↑打印内容↑---------------------'''
str.rindex(sub[, start[, end]])
说明:字符串 str[start:end] 切片中子字符串 sub 的最大索引。 类似于str.find(sub[, start[, end]]),但如果 sub 未被找到则会引发错误,而不是返回-1。
更详细说明请参阅 Python官方文档>str.rindex() 部分。实例如下所示:
print("Hello Hello".rindex("lo"))
print("Hello Hello".rindex("lo", 1))
print("Hello Hello".rindex("lo", 1, 6))
print("Hello Hello".rindex("lo", 1, 3))
'''-------------------↓打印内容↓------------------------
9
9
3
ValueError: substring not found
----------------------↑打印内容↑---------------------'''
str.rjust(width[, fillchar])
说明:用fillchar指定的单一字符*将原字符串扩充为width的长度,原字符串靠右对齐,填补字符在原字符串左边。 如果width小于原字符长度则不做扩充,不指定fillchar则默认用空格字符填补。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.rjust() 部分。实例如下所示:
print("ab".rjust(6, '#'))
print("ab".rjust(5, "*"))
print("abc".rjust(5, "@"))
print("abc".rjust(6, "$"))
'''-------------------↓打印内容↓------------------------
####ab
***ab
@@abc
$$$abc
----------------------↑打印内容↑---------------------'''
str.rpartition(sep)
说明:将字符串 str 以 sep 为间隔符且在 sep 最后一次出现的位置分割成两部分,并返回3个元素的元组。其中包含分隔符之前的部分字符串、分隔符本身,以及分隔符之后的部分字符串。 如果分隔符未找到,则返回的元组中包含字符本身以及两个空字符串。sep 不允许为空字符串。
更详细说明请参阅 Python官方文档>str.rpartition() 部分。实例如下所示:
print("a-b-c".rpartition('-'))
print("abcde".rpartition('c'))
print("abcde".rpartition('bcd'))
print("abcde".rpartition('bcc'))
'''-------------------↓打印内容↓------------------------
('a-b', '-', 'c')
('ab', 'c', 'de')
('a', 'bcd', 'e')
('', '', 'abcde')
----------------------↑打印内容↑---------------------'''
str.rsplit(sep=None, maxsplit=-1)
说明:将字符串 str 从右向左以 sep 为间隔符分割maxsplit指定的次数,并返回maxsplit+1个元素的列表**。如果sep不指定,将以空字符(空格、换行符、制表符等)为间隔符;如果maxsplit不指定,将会分割最大的次数,即找到全部的sep 并分割。
更详细说明请参阅 Python官方文档>str.rsplit() 部分。实例如下所示:
print("a-b-c-d-e".rsplit('-', 2))
print("a-b-c-d-e".rsplit('-'))
print("a++b++c++d++e".rsplit('++'))
print("a++b++c++d++e".rsplit('+'))
print("hello world".rsplit())
print("".rsplit())
'''-------------------↓打印内容↓------------------------
['a-b-c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']
['a', '', 'b', '', 'c', '', 'd', '', 'e']
['hello', 'world']
[]
----------------------↑打印内容↑---------------------'''
str.rstrip([chars])
说明:按照 chars 指定的字符串的任意组合,去除字符串 str 的后缀。如果不指定chars或为None则去除空格。
更详细说明请参阅 Python官方文档>str.rstrip() 部分。实例如下所示:
print('hello world'.rstrip('lrd')) # lrd 可以组合为 rld,所以去掉后缀rld
print('hello world'.rstrip('**l@@r$$d##')) # **l@@r$$d## 可以组合为 rld,所以去掉后缀rld
print('hello world'.rstrip('re')) # re 的所有组合都不是字符串的后缀,所以不会有后缀被去掉
print('hello world'.rstrip('ler')) # ler 的所有组合都不是字符串的后缀,所以不会有后缀被去掉
print('hello wor '.rstrip()) # 不指定参数则去除空格后缀
print('hello wor '.rstrip(None)) # 参数为None则去除空格后缀
print('hello world'.rstrip()) # 不指定参数则去除空格后缀,但并没有空格后缀,所以不会有后缀被去掉
print('hello world'.rstrip(None)) # 参数为None则去除空格后缀,但并没有空格后缀,所以不会有后缀被去掉
'''-------------------↓打印内容↓------------------------
hello wo
hello wo
hello world
hello world
hello wor
hello wor
hello world
hello world
----------------------↑打印内容↑---------------------'''
str.split(sep=None, maxsplit=-1)
说明:将字符串 str 从左向右以 sep 为间隔符分割maxsplit指定的次数,并返回maxsplit+1个元素的列表**。如果sep不指定,将以空字符(空格、换行符、制表符等)为间隔符;如果maxsplit不指定,将会分割最大的次数,即找到全部的sep 并分割。
更详细说明请参阅 Python官方文档>str.split() 部分。实例如下所示:
print("a-b-c-d-e".split('-', 2))
print("a-b-c-d-e".split('-'))
print("a++b++c++d++e".split('++'))
print("a++b++c++d++e".split('+'))
print("hello world".split())
print("".split())
'''-------------------↓打印内容↓------------------------
['a', 'b', 'c-d-e']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']
['a', '', 'b', '', 'c', '', 'd', '', 'e']
['hello', 'world']
[]
----------------------↑打印内容↑---------------------'''
str.splitlines([keepends])
说明:字符串 str 以行边界符
为间隔符进行拆分,并返回一个列表。
行边界符 | 描述 |
---|---|
\n | 换行 |
\r | 回车 |
\r\n | 回车 + 换行 |
\v1 或 \x0b | 行制表符 |
\f1 或 \x0c | 换表单 |
\x1c | 文件分隔符 |
\x1d | 组分隔符 |
\x1e | 记录分隔符 |
\x85 | 下一行 (C1 控制码) |
\u2028 | 行分隔符 |
\u2029 | 段分隔符 |
更详细说明请参阅 Python官方文档>str.splitlines() 部分。实例如下所示:
print("hello\nworld\r\nhello\n\nworld\n\r".splitlines())
print("hello\nworld\r\nhello\n\nworld\n\r".splitlines(keepends=False))
print("hello\nworld\r\nhello\n\nworld\n\r".splitlines(keepends=True))
print("""hello\nworld\r\nhe
llo\n\nworld\n\r""".splitlines())
print(''.splitlines())
print(''.splitlines(), ''.split('\n')) # 与 split() 的区别
print("hello\n".splitlines(), "hello\n".split('\n')) # 与 split() 的区别
'''-------------------↓打印内容↓------------------------
['hello', 'world', 'hello', '', 'world', '']
['hello', 'world', 'hello', '', 'world', '']
['hello\n', 'world\r\n', 'hello\n', '\n', 'world\n', '\r']
['hello', 'world', 'he', 'llo', '', 'world', '']
[]
[] ['']
['hello'] ['hello', '']
----------------------↑打印内容↑---------------------'''
str.startswith(prefix[, start[, end]])
说明:判断字符串 str[start:end] 的末尾是否以prefix子字符串作为后缀结束的。prefix可以是由多个子字符串组成的元组。
更详细说明请参阅 Python官方文档>str.startswith() 部分。实例如下所示:
print("hello,你好".startswith("hello"))
print("你好,hello".startswith("你好"))
print("hello,你好".startswith("ello"))
print("hello,你好".startswith(("aa", "world", "hello")))
'''-------------------↓打印内容↓------------------------
True
True
False
True
----------------------↑打印内容↑---------------------'''
str.strip([chars])
说明:按照 chars 指定的字符串的任意组合,去除字符串 str 两边的前缀与后缀。如果不指定chars或为None则去除空格。
更详细说明请参阅 Python官方文档>str.strip() 部分。实例如下所示:
print('hello world'.strip('lhd')) # lrd 可以组合为 前缀h 与 后缀ld,所以去掉前缀h 与 后缀ld
print('hello world'.strip('**l@@h$$d##')) # **l@@r$$d## 可以组合为前缀h 与 后缀ld,所以去掉前缀h 与 后缀ld
print('hello world'.strip('rle')) # rle 的所有组合都不是字符串的前缀或后缀,所以不会有前缀或后缀被去掉
print('hello world'.strip('hle')) # hle 以组合为 前缀hell,但不是字符串的后缀,所以去掉前缀hell
print(' llo wor '.strip()) # 不指定参数则去除空格前缀或后缀
print(' llo wor '.strip(None)) # 参数为None则去除空格前缀或后缀
print('hello world'.strip()) # 不指定参数则去除空格前缀或后缀,但并没有空格前缀或后缀,所以不会有前缀或后缀被去掉
print('hello world'.strip(None)) # 参数为None则去除空格前缀或后缀,但并没有空格前缀或后缀,所以不会有前缀或后缀被去掉
'''-------------------↓打印内容↓------------------------
ello wor
ello wor
hello world
o world
llo wor
llo wor
hello world
hello world
----------------------↑打印内容↑---------------------'''
str.swapcase()
说明:将字符串 str 中的所有大写转换为小写,所有小写转换为大写。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.swapcase() 部分。实例如下所示:
print("Hello World".swapcase())
print("Hello World".swapcase().swapcase() == "Hello World") # 并不是所有的 str.swapcase().swapcase() == str
'''-------------------↓打印内容↓------------------------
hELLO wORLD
True
----------------------↑打印内容↑---------------------'''
str.title()
说明:将字符串 str 转换为标题的形式(即每个单词的首字母大写,其他字母小写)。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.title() 部分。实例如下所示:
print("hello world".title())
print("CPU".title()) # 单纯的只是从字面上将每个单词首字母大写,其余小写
print("The Yellow River basin is China's birthplace.".title()) # 撇号会被认为单词的边界,可用正则表达式完成预期的结果
结果
'''-------------------↓打印内容↓------------------------
Hello World
Cpu
The Yellow River Basin Is China'S Birthplace.
----------------------↑打印内容↑---------------------'''
str.translate(table)
说明:字符串 str 中的字符按给定的转换表进行映射。可以使用 str.maketrans() 创建字符映射转换表。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.translate() 部分。实例如下所示:
x = "ace"
y = "123"
z = "b"
dicX = {'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 's': '6'}
str0 = str.maketrans(dicX) # 创建字符映射转换表
print("abcde".translate(str0))
dicX = {'a': '1', 'b': None, 'c': '3', 'd': '4', 'e': '5', 's': '6'}
str0 = str.maketrans(dicX) # 创建字符映射转换表
str1 = str.maketrans(x, y) # 创建字符映射转换表
str2 = str.maketrans(x, y, z) # 创建字符映射转换表,并删除指定字符
print("abcde".translate(str0))
print("abcde".translate(str1))
print("abcde".translate(str2))
'''-------------------↓打印内容↓------------------------
12345
1345
1b2d3
12d3
----------------------↑打印内容↑---------------------'''
str.upper()
说明:将字符串中所有字符的小写转换为大写。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.upper() 部分。实例如下所示:
print("hello world".upper())
print("Hello world".upper())
'''-------------------↓打印内容↓------------------------
HELLO WORLD
HELLO WORLD
----------------------↑打印内容↑---------------------'''
str.zfill(width)
说明:用ASCII码中的数字 ‘0’ 在原字符串左边填充,并扩充为width的长度。 正负值前缀 (’+’/’-’) 的处理方式是在正负符号 之后 填充而非在之前。如果width小于原字符长度则不做扩充。结果为新的字符串对象。
更详细说明请参阅 Python官方文档>str.zfill() 部分。实例如下所示:
print("123".zfill(5))
print("+123".zfill(5))
print("-123".zfill(5))
print("abc".zfill(5))
print("+abc".zfill(5))
print("-abc".zfill(5))
print("字符".zfill(5))
print("字符串".zfill(5))
print("+字符串".zfill(5))
print("-字符串".zfill(5))
'''-------------------↓打印内容↓------------------------
00123
+0123
-0123
00abc
+0abc
-0abc
000字符
00字符串
+0字符串
-0字符串
----------------------↑打印内容↑---------------------'''
参考资料(如有侵权,请联系作者删除内容):