常用的几个方法
① capitalize()
把字符串的首字母大写
例:
a="hello"
print(a.capitalize())
输出结果:”Hello“
② center(width)
用法:str.center(width,指定字符)
将原字符串用空格填充成一个长度为width的字符串,原字符串内容居中。
例:
a= 'hello'
print(a.center(10))
输出结果: hello #两边有空格,内容居中
例:
a= 'hello'
print(a.center(11,"$"))
输出结果:”$$$hello$$$“
③ count()
用法:str.count(sub, start,end))
返回字符串s在str中出现的次数
例:
a= "hello"
print(a.count('l'))
输出结果”:”2“
例:
a= "hello"
print(a.count('l',3))
输出结果:”1“
④strip()
返回截掉字符串的空格或指定字符后生成的新字符串,lstrip去除左侧指定字符,rstrip去除右侧指定字符。
例:
a= " hello "
print(a.strip())
输出为:
“hello”
例:
a=" hello "
print(a.lstrip())
输出为:“hello ”
例:
a= " hello "
print(a.rstrip())
输出为:“ hello”
⑤endswith()/startswitch()
判断字符串str是否以字符串s结尾/开始
例:
a='hello'
print(a.startswith('h'))
print(a.endswith('b'))
输出结果:True
False
⑥find()与index()
用法:string.find(str, beg=0, end=len(string))
检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1。
index的用法与find相同,区别在于如果未找到会报错。
例:
a="hello python"
print(a.find('l'))
输出结果:“2”
例:
a="hello python"
print(a.find('b'))
输出结果:“-1”
例;a="hello python"
print(a.index('b'))
报错
⑦lower()与upper()
lower():将字符串中所有大写字符为小写
upper():将字符串中所有小写字符为大写
例:
a="Hello"
print(a.lower())
print(a.upper())
输出结果:hello
HELLO
举报/反馈