字符串、列表、元组、字典、集合常用函数与方法汇总
文章目录
- 字符串、列表、元组、字典、集合常用函数与方法汇总
- 一级目录
-
- 二级目录
- 字符串常用函数和方法
-
- capitalize()
- count(sub[, start[, end]])
- encode(encoding="utf-8", errors="strict")
- find(sub[, start[, end]])
- index(sub[, start[, end]])
- isalnum()
- isalpha()
- isdigit()
- islower()
- isnumeric()
- isspace()
- isupper()
- join(iterable)
- len()**函数**
- lower()
- lstrip(chars)
- min(str)函数
- replace(old, new[, count])
- split(sep=None, maxsplit=-1)
- swapcase()
- upper()
- 列表常用函数和方法
- 常用的元组函数和方法
- 常用的字典函数及方法
- 常用集合方法与函数
一级目录
二级目录
三级目录
字符串常用函数和方法
capitalize()
返回字符串副本,将字符串的首个字符大写,仅对英文字符有效
a = "iloveyou"
b = "王asdf123"
print(a.capitalize()) # Iloveyou
print(b.capitalize()) # 王asdf
center(width[, fillchar]) 返回字符串副本,设定字符串长度,并将调用此方法的字符串居中,可设定两边填充字符串的样式
print(a.center(20))
print(b.center(20,"#"))
count(sub[, start[, end]])
统计输入的参数在调用此方法的字符串中出现的次数,将次数返回,可选择检测字符串的起始和结束位置
print(a.count("o")) # 2
print(a.count("o",5,-1)) # 1
encode(encoding=“utf-8”, errors=“strict”)
返回原字符串编码为字节串对象的版本,以 encoding 指定的编码格式对字符串进行编码。 默认编码为 ‘utf-8’。 可以给出 errors 来设置不同的错误处理方案。 errors 的默认值为 ‘strict’,表示编码错误会引发UnicodeError。 其他可用的值为 ‘ignore’, ‘replace’,‘xmlcharrefreplace’, ‘backslashreplace’ 以及任何其他通过 codecs.register_error() 注册的值。
print(a.encode()) # b'iloveyou'
find(sub[, start[, end]])
返回sub参数在字符串中第一次被找到的位置,可指定查找字符串的起始和结束的位置。如果sub未被找到,则返回-1,可指定查找的起始和结束位置,找到sub后会立刻停止查找并返回。
print(a.find("o")) # 2
print(a.find("o", 5, -1)) # 6
index(sub[, start[, end]])
类似于 find(),但在找不到子类时会引发 ValueError。
print(a.index("1")) # ValueError: substring not found
isalnum()
检测字符串是否全部由字符(包含英文字符,中文和数字)组成,返回布尔类型的值
print(b.isalnum()) # True
isalpha()
检测字符串是否全部由字符(包含英文字符和中文)组成,返回布尔类型的值
print(a.isalpha()) # True
print(b.isalpha()) # False
isdigit()
检测字符串是否全部由数字组成,返回布尔类型的值
print("123".isdigit()) # True
print(a.isdigit()) # False
islower()
检测字符串是否全部为小写组成,返回布尔类型的值,中文和数字对检测结果无影响
print(a.islower()) # True
print(b.islower()) # True
print("ASSDFF".islower()) # False
isnumeric()
检测字符串是否只由数字组成。这种方法是只针对unicode对象。
注:定义一个字符串为Unicode,只需要在字符串前添加 ‘u’ 前缀即可,具体可以查看本章节例子。
str = u"this2009"
print(str.isnumeric()) # False
str = u"23443434"
print(str.isnumeric()) # True
isspace()
检测字符串是否只由空格组成。
print(" ".isspace()) # True
isupper()
检测字符串是否只有大写字符组成。
print("ASDFGHH".isupper()) # True
join(iterable)
使用指定的字符串,把一个容器中的元素链接成一个字符串,返回字符串副本,如果 iterable 中存在任何非字符串值包括 bytes 对象则会引发 TypeError
str1 = ["我", "爱", "学", "习"]
print("*".join(str1)) # 我*爱*学*习
len()函数
检测字符串的长度
print(len("123")) # 3
lower()
返回原字符串的副本,其所有区分大小写的字符均转换为小写。
print("ILOVEYOU".lower()) # iloveyou
lstrip(chars)
返回原字符串的副本,移除其中的最左侧字符。 chars 参数为指定要移除字符的字符串。 如果省略或为 None,则 chars 参数默认移除空格符。 实际上chars 参数并非指定单个前缀;而是会移除参数值的所有组合:
print(" 你好!".lstrip()<