capitalize()方法

 capitalize() 将字符串的第一个字母变成大写,其他字母变小写。

str.capitalize()

返回值

该方法返回一个首字母大写的字符串。

实例

#!/usr/bin/python3

str = "this is string example."

print ("str.capitalize() : ", str.capitalize())

输出结果如下:

#!/usr/bin/python3

str = "this is string example from runoob....wow!!!"

print ("str.capitalize() : ", str.capitalize())
 

PS:首字符如果是非字母,首字母不会转换成大写

str1 = "123Hello world"
print(str1.capitalize())

输出结果:

123hello world

center()方法

str.center(width[, fillchar])

返回一个指定的宽度 width 居中的字符串,如果 width 小于字符串宽度直接返回字符串,否则使用 fillchar 去填充,fillchar只能是单字符。

实例

#!/usr/bin/python3
tr = "Hello python"
print(str.center(40, "*"))

以上实例输出结果如下:

**************Hello python**************

count()

用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

扫描二维码关注公众号,回复: 1355055 查看本文章
str.count(sub, start= 0,end=len(string))

参数

  • sub -- 搜索的子字符串
  • start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
  • end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

返回值

该方法返回子字符串在字符串中出现的次数。

实例

#!/usr/bin/python3
str = "abbcccdddd"
print(str.count("b"))
print(str.count("bb", 0, 5))

输出结果如下:

2
1