len
len() 方法返回对象(字符、列表、元组等)长度或项目个数
字符串长度 len
text = "hello"print(len(text)) #字符串长度
5
列表元素个数 len
text = [1,2,3,4,5]print(len(text)) #列表元素个数
5
字符串
截取
字符出现次数 count
str.count(字符串, 开始搜索位置=0, 结束搜索位置=最后一个字符)
text = 'hello'print(text.count('l',0,1)) #前两个字符不包含l字符print(text.count('l',0,len(text))) #搜索所有字符print(text.count('l',0)) #搜索所有字符,简写,不填默认最后一个字符
0 2 2
截取单个字符 []
text = 'Hello'print(text[0]) #截取第一个字符print(text[4]) #截取最后一个字符
H o
截取指定范围 [:]
text = 'Hello'print(text[1:4]) #截取范围字符print(text[:4]) #索引前的所有字符(包括索引)print(text[3:]) #索引后的所有字符(包括索引)
ell Hell lo
填充字符串并居中 center
text = 'hello'print(text.center(11,'-')) #填充字符串并居中
—-hello—-
靠后的字母 max
text = 'Hello'print(max(text))
o
靠前的字母 min
text = 'aHello'print(min(text)) #内部顺序依据是 !#$0123456789ABCDEFGabcdefg
H
字符串连接 +
text = 'Hello'print(text + "! Wonvy!") #字符串连接
Hello! Wonvy!
字符串重复 *
text = 'Hello'print(text * 2) #重复输出字符串'print(text * 3)
HelloHello HelloHelloHello
判断
包含指定字符 in
text = 'Hello'print('l' in text) #如果包含l字符,返回True,否则返回Falseprint('L' in text) #如果包含L字符,返回True,否则返回False
True False
不包含指定字符 not in
text = 'Hello'print('l' not in text) #如果不包含l字符,返回True,否则返回Falseprint('L' not in text) #如果不包含L字符,返回True,否则返回False
False True
全为字母或数字 且不为空 isalnum()
text = ''print(text.isalnum()) #Falsetext = 'Hello123'print(text.isalnum()) #Truetext = 'Hello 'print(text.isalnum()) #Falsetext = 'Hello.'print(text.isalnum()) #False
False True False False
全为字母 且不为空 isalpha()
text = ''print(text.isalpha()) #Falsetext = 'Hello123'print(text.isalpha()) #Falsetext = 'Hello'print(text.isalpha()) #True
False False True
大小写转换
第一个字母大写 capitalize
text = 'hello'print(text.capitalize()) #第一个字母大写
Hello
翻转大小写 swapcase
text = 'Hello'print(text.swapcase()) #翻转大小写
hELLO
全转为小写字母 lower
text = 'Hello'print(text.lower()) #转为小写字母
hello
全转为大写字母 upper
text = 'Hello'print(text.upper()) #转为大写字母
HELLO
删除右边空格 rstrip
text = 'Hello 'print(text.rstrip()) #删除右边空格
Hello
删除左边空格 lstrip
text = ' Hello 'print(text.lstrip()) #删除左边空格
Hello
删除两侧空格或指定符号 strip
text = " hello "; # 去除首尾空格print text.strip();text = "00000hello00000";print text.strip('0'); #去除首尾字符 0text = "-----hello wonvy-----";print text.strip('0'); #去除首尾字符 -
hello hello ——-hello wonvy——-
