count():获取字符串中某个字符的数量。
str = 'python_count'
str.count('o')
>>> 2
strip():删除字符串首位的空格,以及换行。
str1 = ' hello python '
str2 = 'hello python '
str3 = ' hello python'
str1.strip()
str2.strip()
str3.strip()
>>> 'hello python'
split():默认情况下在字符串中有空格的位置将字符串切割生成一个列表,有参数时,在参数处进行切割。
str1 = 'hello python'
str2 = 'hello,python'
str3 = 'hellopython'
lst1 = str1.split()
lst2 = str2.split(',')
lst3 = str3.split('o')
print(lst1,lst2,lst3)
>>> ['hello','python'] ['hello','python'] ['hell','pyth','n']
upper() & lower():前者将字符串中每个英文变成大写,后者将字符串中每个英文变成小写。
str = 'hello_PYTHON'
str.upper()
>>> 'HELLO_PYTHON'
str.lower()
>>> 'hello_python'
__len__():相当于内置函数len(),获得字符串包括字符的数量。
str = 'hello python'
str.__len__()
>>> 12
>>>'hello python'.__len__()
>>> 12
len(str)
>>> 12
str.format():格式化字符串函数
#将参数依次填入字符串中
>>>'{} {}'.format(hello,python)
>>> 'hello python'
#规定每个位置传入参数
>>>'{1} {2},{1} {3}'.format(hello,world,python)
>>> 'hello world,hello python'
#格式化浮点(float)类型参数为字符串,并规定小数位数
str = '{:.2f}'.format(math.pi)
print(str)
>>> 3.14
#通过字典设置带参数名参数
>>>'{name}今年{age}岁'.format(name = '张三',age = '5')
>>> '张三今年5岁'