常用的字符串的方法

本文详细介绍了Python中字符串的各种操作方法,包括判断方法如isdigit()和isalpha(),计数方法count(),查找方法find()和index(),格式调整方法center()、strip()及其变形,替换方法replace(),以及起始检查方法startswith()。通过实例展示了每个方法的使用场景和效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串的方法:
s.isdigit() 判断是否是数字组成>> str= “223121” print(str.isdigit())>> ture 如果str 不是数字则为false
s.isalpha() 判断是否由字母组成>>
s.count() 判断字符串中有多少个sum #str = “this is string example…wow!!!” ,
sub = “s”
print ("str.count(sub, 4, 40) : ", str.count(sub, 1, 40))>> str.count(sub, 4, 40) : 3

s.find() 查找字符串所在位置的下标 str1 = “ths is exampl e…iiiiiii…wow!!!”
str2 = “i”
print (str1.find(str2))>>>4
s.index() 索引 str=“jkhffdsf” str[1:6]>>>khffds

s.center()      居中          str ="“[www.runoob.com] ”                         "
				print(str.center(60))

s.strip() # 去左右两端的某些字符(默认是空白字符) str =" “[www.runoob.com] ” "
print(str.strip(" "))>>>“[www.runoob.com] ”

strip、rstrip、lstrip是python字符串中的方法。从字面可以看出r=right,l=left。
strip函数返回字符串副本,该副本是从字符串两边删除了参数指定字符后的字符串,不带参数进去则是去除两边的空格。。
rstrip函数返回字符串副本,该副本是从字符串最右边删除了参数指定字符后的字符串,不带参数进去则是去除最右边的空格。
lstrip函数返回字符串副本,该副本是从字符串最左边删除了参数指定字符后的字符串,不带参数进去则是去除最左边的空格。

s.replace(old,new,count) S = “this is string example…wow!!!”
print (S.replace(“is”, “was”, 3))>>>thwas was string example…wow!!!

s.startswith() str = “this is string example…wow!!!”
print (str.startswith( ‘this’ )) # 字符串是否以 this 开头 ture
print (str.startswith( ‘string’, 8 )) # 从第八个字符开始的字符串是否以 string 开头 ture
print (str.startswith( ‘this’, 0, 3 )) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头 ture

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值