转载:https://www.cnblogs.com/hukey/p/9612961.html
字符串的操作方法:
1. capitalize() :首字母大写
s1 = 'my heart will go on' print(s1.capitalize()) # 首字母大写 # 执行结果: # My heart will go on
2 upper() : 全部大写
s1 = 'my heart will go on' print(s1.upper()) # 全部转为大写 # 执行结果: # MY HEART WILL GO ON
3 lower() : 全部小写
4 title(): 标题首字母大写
5 center(): 居中,默认填充空格
6 count():统计字符串出现个数
s1 = 'adfasdfasdfasdfertadf' print(s1.count('a')) # 统计字符串出现的次数 # 执行结果: # 5
7 split(): 按照指定字符分隔成多个元素 str --> list
s1 = 'nice to meeting you' print(s1.split()) # 默认将字符串通过空格分隔并组成列表类型 # 执行结果: # ['nice', 'to', 'meeting', 'you']
9 replace(): 字符串替换
s1 = 'nice to meeting you' print(s1.replace('meeting', 'see')) # 在字符串中,用第一个参数替换掉第二个参数,默认是匹配上则全部替换 # 执行结果: # nice to see you
10 find() 和 index()
find() 和 index() 都是通过元素找索引的方法,区别如下:
find()方法:元素存在打印索引,元素不存在返回 -1
index()方法:元素存在打印索引,元素不存在报错。错误信息:ValueError: substring not found
s1 = 'nice to meeting you' print(s1.find('to')) # 执行结果: # 5 print(s1.find('xxx')) # 执行结果: # -1 print(s1.index('to')) # 执行结果: # 5 # print(s1.index('xxx')) # 执行结果: # ValueError: substring not found