capitalize()
首字母大写,其他字母小写
str1 = 'alex is a bird' print (str1.capitalize()) 计算结果: Alex is a bird
swapcase()
大小写反转
>>> str1 = "Alex is a bird" >>> print(str1.swapcase()) 计算结果: aLEX IS A BIRD
title()
非字母隔开的部分,首字母大写,其余字母小写
>>> str1 = "Alex is a bird" >>> print(str1.title()) 计算结果: Alex Is A Bird
upper()
全部大写
>>> str1 = "Alex is a bird" >>> print(str1.upper()) 计算结果: ALEX IS A BIRD
lower()
全部小写
>>> str1 = "Alex is a bird" >>> print(str1.lower()) 计算结果: alex is a bird
center()
内容居中显示,填充物默认为空
>>> str1 = "Alex is a bird" >>> print(str1.center(20)) #不够20个字符,用空格表示 >>> print(str1.center(20,"*")) ##不够20个字符,用*表示 计算结果: Alex is a bird ***Alex is a bird***
find()
通过元素找索引,可以整体找,可以切片,找不到则返回-1
>>> str1 = "Alex is a bird" >>> print(str1.find('bird')) #字符串中寻找bird,返回匹配到的第一个字母的索引 >>> print(str1.find('Alex'))>>> print(str1.find('xxx')) #如果匹配不到,返回-1 >>> print(str1.find('Bird',1,5)) #在第一个索引和第5个索引中寻找 计算结果: 10 0 -1 -1
index()
通过元素找索引,可以整体找,可以切片,找不到会报错
>>> str1 = "Alex is a bird" >>> print(str1.index("Alex")) >>> print(str1.index("xxx")) #匹配不到报错 计算结果: 0Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
startswith(obj)
检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。
>>> str1 = "Alex is a bird" >>> print(str1.startswith("A")) 计算结果: True
endswith(obj)
检查字符串是否是以 obj 结尾,是则返回 True,否则返回 False。
>>> str1 = "Alex is a bird" >>> print(str1.endswith("bird")) 计算结果 True
strip()
去除字符串前后两端的空格或其他字符,换行符,tab键等
>>> str1 = "***Alex***" >>> print(str1.strip("*")) #去除两边的* >>> print(str1.lstrip("*")) #去除左边的* >>> print(str1.rstrip("*")) #去除右边的* 计算结果 Alex Alex*** ***Alex
replace(oldstr, newstr)
替换字符串
>>> str1 = "Alex is a bird" >>> print(str1.replace("bird","dog")) #将bird改为dog 计算结果 Alex is a dog
isalpha()
字符串只由字母组成
>>> str1 = "Alex" >>> print(str1.isalpha()) True >>> str1 = "Alex is a bird" >>> print(str1.isalpha()) #字符串中包含空格,所以为False False
isdigit()
字符串只由数字组成
>>> str1 = "alex" >>> print(str1.isdigit()) False >>> str1 = "110" >>> print(str1.isdigit()) #字符串如果都为数字,为True True
format()
格式化字符串
方式一:按位置传参 >>> str1 = '我叫{},今年{}岁' >>> str2 = '我叫{},今年{}岁'.format('Alex',53) >>> print(str2)我叫Alex,今年53岁方 式二:按索引传参 >>> str1 = '我叫{0},今年{1}岁,大家都叫我{0}' >>> str2 = '我叫{0},今年{1}岁,大家都叫我{0}'.format('alex',53) >>> print(str2)我叫alex,今年53岁,大家都叫我alex 方式三:按key传参 >>> str1 = '我叫{name},今年{age}岁' >>> str2 = '我叫{name},今年{age}岁'.format(age=53,name='Alex') >>> print(str2)我叫Alex,今年53岁
count()
统计元素在字符串出现的次数
>>> str1 = "Alex is a bird" >>> print(str1.count('i')) #统计字母i在字符串中出现的次数2split() 分割
name = 'aleX leNb' print(name.split('l')) ['a', 'eX ', 'eNb']
name = 'aleX leNb' print(name.split('l',1)) ['a', 'eX leNb']