capitalize()将字符串的第一个字母变成大写,其他字母变小写。
用法:
str.capitalize()
代码及运行结果:
str1 = "my name is Da Da NIU" print(str1.capitalize())
输出:My name is da da niu
-----------------------------------------
center() 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
center()方法语法:
str.center(width[], fillchar)
- width -- 字符串的总宽度。
- fillchar -- 填充字符。
str = "wo shi da da niu " print ("str.center(40, '*') : ", str.center(40, '*'))
输出:***********wo shi da da niu ************
----------------------------------------------------------------------
count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
使用方法
str.count(sub, start= 0,end=len(string))
- sub -- 搜索的子字符串
- start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
- end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
str="xue wu zhi jing shi zhong guo de yi ge yan yu,shi wo men ying gai xue xi de " sub='o' print ("str.count('o') : ", str.count(sub)) sub='shi' print ("str.count('shi', 开头,结尾 ) : ", str.count(sub,0,len(str)))
str.count('o') : 3
str.count('run', 0, 10) : 2