字符串的方法:
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