字符串中常见的函数
- capitalize()将字符串第一个字母变为大写
s = 'abcdef0'
s.capitalize()
'Abcdef0'
- casefold()将字符串里所有字母小写
s2 = 'ABCDEF'
s2.casefold()
'abcdef'
- cente(width)将字符串居中长度为width
s2 = 'ABCDEF'
s2.center(30)
' ABCDEF '
- count(s)查找s在字符串中出现的次数
s2 = 'ABCDEF'
s2.count('A')
1
- endswith(s)检查字符串是否以s结尾
s2 = 'ABCDEF'
s2.endswith('F')
True
- expandtabs()把字符串中tab符号(\t)转化为空格
s3 = 'abc\tdef\tg'
s3.expandtabs()
'abc def g'
- find()查询字符串中是否包含
s = 'abcde'
s.find('a')
0
s.find('Y')
-1
- join(123)以123为分割将其他字符串插入
s = 'abc'
s.join('123')
'1abc2abc3'
- repalace(old,new)将old替换为new
s = 'abcd f'
s.replace('f','e')
'abcd e'
- split()默认用按照空格将字符串切片,可添加参数进行切片
s = 'a b c d'
s.split()
['a', 'b', 'c', 'd']
- swapcase()反转大小写
s = 'AbCd'
s.swapcase()
'aBcD'
- title()将所有单词首字母大写其余字母小写
s = 'where are you'
s.title()
'Where Are You'
字符串格式化函数format
格式化字符串 format
'{0},{1},c'.format('a','b')
'a,b,c'
'{{0}}'.format('a')
'{0}'