关于 Python 的字符串处理相关的方法还是非常多的,由于我正在学习 Python,于是就把 Python 中这些混杂的用于 string 的函数总结出来,在自己忘记的时候便于查找,希望对于有类似需求的人有所帮助。
captalize() 函数
功能
将一个字符串的第一个字母大写
用法
str.captalize()
参数
无
返回值
string
示例代码
str = "hello world!"
print "str.capitalize(): ", str.capitalize()
运行结果
tr.capitalize(): Hello world!
center(width, fillchar) 函数
将字符串居中,居中后的长度为 width
功能
将字符串居中,居中后的长度为 width
用法
str.center(width[, fillchar])
参数
- width: 表示字符串总长度
- fillchar: 使字符串居中所填充的字符,默认为空格
返回值
返回填充字符后的字符串
示例代码
str = "hello world!"
print "str.center(20): ", str.center(20)
print "str.center(20,'-'): ", str.center(20,'-')
运行结果
tr.center(20): hello world!
str.center(20,'-'): ----hello world!----
count(str, start=0, end=len(string)) 函数
功能
返回该字符串中出现某字符串序列(或字符)的次数
用法
str.count(sub, start=0, end=len(string))
参数
- sub: 被查找的字符串序列
- start: 开始查找的索引位置,默认为字符串开始
- end: 结束查找的索引位置,默认为字符串结束
返回值
被查找的序列在字符串的查找位置中出现的次数
示例代码
str = "hello world! hello world!"
sub = "o"
print "str.count(sub): ", str.count(sub)
sub = "hello"
print "str.count(sub, 5) ", str.count(sub, 5)
运行结果
str.count(sub): 4
str.count(sub, 5) 1