2017年05月11日
阅读: 3226
Python字符串的常用方法说明
友情提醒:本文最后更新于 2781 天前,文中所描述的信息可能已发生改变,请谨慎使用。
1.capitalize():字符串首字符大写
>>> string = 'this is a string.'
>>> string.capitalize()
This is a string.
2.center(width, fillchar=None):将字符串放在中间,在指定长度下,首尾以指定字符填充
>>> string = 'this is a string.'
>>> string.center(30,'*')
'********this is string********'
3.count(sub, start=None, end=None):计算字符串中某字符的数量
>>> string = 'this is a string.'
>>> string.count('i', 0, 5)
1
# start 和 end 参数为索引
4.endswith(self, suffix, start=None, end=None):判断是否以某字符结尾
>>> string = 'this is a string.'
>>> string.endswith('ing.')
True
>>> string.endswith('xx')
False
5.find(self, sub, start=None, end=None):在字符串中寻找指定字符的位置
>>> string = 'this is a string'
>>> string.find('a')
8 # 查找的字符存在时返回其索引,空格也占索引
>>> string.find('x')
-1 # 查找的字符不存在时返回-1
6.format(*args, **kwargs):类似%s的用法,它通过{}来实现
>>> string = 'My name is {0},my job is {1}.'
>>> string.format('yang','python engineneer')
My name is yang,my job is python engineneer.
>>> string2 = 'My name is {name},my job is {job}.'
>>> string2.format(name='yang',job='python engineneer')
My name is yang,my job is python engineneer.
7.index(self, sub, start=None, end=None):类似find
>>> string = 'this is a string.'
>>> string.index('a') # 找的到的情况
8
>>> string.index('xx') # 找不到的情况,程序报错
ValueError: substring not found
8.title():将字符串的单词首字母大写
>>> string = 'this is a string'
>>> string.title()
'This Is A String'
9.lower():将字符串的所有字母小写
>>> string = 'This Is A String'
>>> string.lower()
'this is a string'
10.upper():将字符串的所有字母大写
>>> string = 'this is a string'
>>> string.uppper()
'THIS IS A STRING'
11.zfill(self, width):返回指定长度的字符串,原字符串右对齐,前面填充0
>>> string = "my name is yang."
>>> string.zfill(18)
'00my name is yang.'
12.split(self, sep=None, maxsplit=None):通过指定分隔符对字符串进行切片
>>> string = "haha lala gege"
>>> string.split(' ')
['haha', 'lala', 'gege']
>>> string.split(' ', 1 ) # 只切分一次
['haha', 'lala gege']
13.strip(self, chars=None):移除字符串头尾指定的字符(默认为空格)
>>> string = " My name is yang"
>>> string.strip()
'My name is yang'
>>> string.strip('g')
' My name is yan'
14.swapcase(self):对字符串的大小写字母进行转换
>>> string = 'This IS a String'
>>> string.swapcase()
'tHIS is A sTRING'
15.startswith(str, beg=0, end=len(string)):判断是否以某字符开始
>>> string = 'this is a string.'
>>> string.startswith('this')
True
>>> string.startswith('xx')
False
上一篇:Python列表的常用方法
下一篇:Django项目常用验证及写法