python string_2 内建函数详解

先定义2个字符串变量

1 #coding:utf-8
2 
3 s1="http"
4 s2="http://www.cnblogs.com/sub2020/p/7988111.html"

取得字符串长度,备用

print "len(s1):%d , len(s2):%d" %(len(s1),len(s2))

输出

len(s1):4 , len(s2):45

# string.split(str="", num=string.count(str))

#以 str 为分隔符切片 string,如果 num有指定值,则仅分隔 num 个子字符串

list1 = s2.split("/")  #使用 '/'为分隔符
print list1
for x,y in enumerate(list1):  #输出带索引的list切片
    print "list[%d]:%s" %(x,y)

output

list[0]:http:
list[1]:
list[2]:www.cnblogs.com
list[3]:sub2020
list[4]:p
list[5]:7988111.html

string.capitalize() 把字符串的第一个字符大写

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

output 第一个字符变为大写了

s1.capitalize() : Http

string.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

print "s1.center(10,'*') :", s1.center(10,"*")
#当width<len时,原样返回str
print "s1.center(2)     :", s1.center(2)
print "s1.center(5)     :", s1.center(5)

output 当长度小于字符串长度时,无变化

s1.center(10,'*') : ***http***
s1.center(2)     : http
s1.center(5)     :  http

# string.count(str, beg=0, end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数

01.计算'c'在s2中出现的次数,后两个参数beg=起始计算位置,默认为[0],end=终止计算位置,默认为字符串长度[len(string)],以s2为例即[44](45-1)

print "s2.count('c') :%d" %s2.count('c')

output 全字符串检索'c'

s2.count('c') :2

02.计算'c'在s2中出现的次数,只设置一个参数,默认为beg参数,end参数为默认值

print "s2.count('c',15) :%d" %s2.count('c',15)

output 从第[15]位检索'c'的出现次数:1次,过滤掉了[15]位之前的一次

s2.count('c',15) :1

03.检索'p'在[10]-[30]间出现的次数

print "s2.count('p',10,30) :%d" %s2.count('p',10,30)

output 

s2.count('p',10,30) :0

# string.find(str, beg=0, end=len(string))
#检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1

01.在s2中全文寻找'c'

print "s2.find('c') :%d" %s2.find('c')

输出 'c'的索引,找到一个就停止

s2.find('c') :11

02.从索引[15]向后寻找'c'

print "s2.find('c',15) :%d" %s2.find('c',15)

output 找到了第二个'c'

s2.find('c',15) :19

03.在[15]-[30]之间寻找'c'

print "s2.find('p',10,30) :%d" %s2.find('p',10,30)

output

s2.find('p',10,30) :-1

发布至首页候选区需要字数,哎,我就是想试试,同时也是自学的一部分

让大家见笑了,如果有错误,请指正,新手,有可能某些地方理解错误

如果您感觉对您有帮助,需要后续,请留言,因为我这么写是把代码拆开详细解释了,源代码都在一起的,以后会整体发布

谢谢捧场!

quote:http://www.runoob.com/python/python-strings.html

原文地址:https://www.cnblogs.com/sub2020/p/7998661.html