Python 字符串的常用方法、字符串的查找和替换

字符串的查找和替换

在这里插入图片描述

查找

检查字符串是否是以 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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值