常用的字符串内建函数(一)

1、capitalize()方法

将字符串的首字母转换为大写,其他字母为小写 ,首字符如果是非字母,首字母不会转换成大写,会转换成小写

用法str.capitalize()

 

2、swapcase()方法

将大写字母转换为小写字母,将小写字母转换为大写字母

用法:str.swapcase()

str1 = "Study"
str2 = "study"
str3 = "sTUDY"
str4 = "123Study"
print(str1.swapcase())
print(str2.swapcase())
print(str3.swapcase())
print(str4.swapcase())

 

 3、replace()方法

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法:replace(old, new[, max])

  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次

str5 = "There is example,There is example,There is example,There is example"

print(str5.replace("is", "was", 3))

 

 

4、find()方法与rfind()方法

从左至右查找字符串中是否包含子字符串,如果指定开始(beg)和结束(end)范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。

语法:str.find(str, beg=0, end=len(string))

str -- 指定检索的字符串

beg--开始索引位置,默认为0

end--结束索引,默认为字符串的长度

str5 = "There is example,There is example,There is example,There is example"
str6 = "is"
print(str5.find(str6, 0, 5))
print(str5.find(str6, 5))
print(str5.find(str6, 10))

 

 rfind()方法 :与find()方法类似,返回字符串最后一次出现的位置,如果没有匹配项则返回-1。 rfind()方法是从右侧开始查找

5、count()方法

用于统计字符串中某字符出现的次数,可选参数为字符串搜索的开始位置和结束位置

返回值:该方法返回子字符串在字符串中出现的次数

语法:str.count(sub,start =0 ,end = len(string))

sub:搜索的子字符串

start:字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。

end:字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置

str5 = "There is example,There is example,There is example,There is example"
sub = "is"
print(str5.count(sub))
print(str5.count(sub, 0, 5,))

 

转载于:https://www.cnblogs.com/keepkeep/p/11570460.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值