几个重要的字符串操作函数(学习Python 第11天)

1.find()

检测str是否包含在mystr中,true返回开始的索引值,false则返回-1

>>>word = 'hello my world!'
>>>word.find('my')
6
>>>word.find('my',7,10)
-1

2.index()

和find用法一样,true返回开始的索引值,false则返回异常

3.count()

返回在start和end之间,str出现的次数

>>>mystr = 'hello my world that is a happily world!'
>>>mystr.count('world')
2

4.replace()

将mystr中的str1替换成str2,如果count制定,则替换不超过count次

>>>mystr = 'hello world hei hei hei!'
>>>mystr.replace('hei','ha',2)
'hello world ha ha hei'

5.split(str)

以str为分隔符,将一大串字符串分割成n个字符串,十分重要

>>>mystr = 'hello world ha ha!'
>>>mystr.split()
['hello','world','ha','ha!']

6.join()

和split()功能相反,在每个字符后面插入str,即将字符串列表重构为字符串,十分重要

>>>str = ' '
>>>li = ['my','name','is','dog']
>>>str.join(li)
'my name is dog'
>>>str = '_'
>>>str.join(li) 
'my_name_is_dog'

7.startswith、endswith

检查字符串是否以str开头或结尾,是返回true,否返回false

>>>mystr = 'hello world ha ha!'
>>>mystr.startswith('hello')
True
>>>mystr.endswith('ha!')
True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值