字符串的查找和替换
查找
检查字符串是否是以 he 开头
sel1 = "helloworld"
print(sel1.startswith('he')) #检查字符串是否是以 he 开头,是则返回 True
运行结果:
True
检查字符串是否是以 d 结束
sel2 = "helloworld"
print(sel2.endswith('d')) #检查字符串是否是以 d 结束,是则返回 True
运行结果:
True
检测 r 是否包含在 sel3 中
sel3 = "helloworld"
print(sel3.find("r",0,len(sel3))) #检测 r 是否包含在 sel3 中,如果 start 和 end 指定范围,则检 查是否包含在指定范围内,如果是返回开始的索引值,否则返回 -1
运行结果:
7
从右边开始查询
sel4 = "helloworld"
print(sel4.rfind("h",0,len(sel4))) #类似于 find(),不过是从右边开始查找
运行结果: 返回的依旧是下标(下标是从左开始数的)
0
index查询
sel5 = "helloworld"
print(sel5.index("e")) #跟 find() ⽅法类似,不过如果 str 不在 string 会报错
运行结果:
1
从右边开始的index查询
sel6 = "helloworld"
print(sel6.rindex("e")) #类似于 index(),不过是从右边开始
运行结果:
1
替换
把sel7中的空格替换成减号
sel7 = "hello world he"
print(sel7.replace(" ","-",1))
(空格分别在“o”和“d”后面)
把 sel7 中的 " " 替换成"-",如果 num 指定 (num指的是括号中最后一个值:1),则替换不超过 num 次 (这里只替换1次)
运行结果:
hello-world he