S为变量
S.find('sub') --> 返回该元素最小的索引
S.index('sub') --> 返回该元素最小的索引
区别:index索引不存在的值时会报错,find会返回-1
案例:
s = 'this is a book'
a = s.find('o')
b = s.index('i')
print(a,b)
输出结果:11,2
S.replace(old, new,[count]) --> 替换
S.replace('old', 'new',替换次数)-->默认次数,全部替换
案例:
s = 'this is a book@'
b=s.replace('@','')
print(b)
输出结果:this is a book
S.split(sep=None) --> 以sep来分割字符串,并返回列表。sep默认为None,分割默认为空格
S.split(sep='以什么字符分割')
案例:
s = 'this is a book'
a = s.split(sep="i")
print(a)
输出结果:['th', 's ', 's a book']
S.startswith(prefix[, start[, end]]) --> 判断字符串是否以前缀开始,返回为bool值。
S.startswith('以什么开头',下标从什么时候开始)
S.endswith(suffix[, start[, end]]) --> 判断字符串是否以尾缀结束,返回为bool值。
S.endswith('以什么结尾',头,尾)#【头,尾)半开半闭区间
案例:
s = 'this is a book'
a = s.startswith("t",0)
b = s.endswith("k",-1)
c = s.endswith("book",-4)
print(a,b,c)
输出结果:True True True
S.lower() --> 将字符串全部转为小写,只针对英文大小写
S.upper() --> 将字符串全部转为大写,只针对英文大小写
S.lower() .upper() #链式调用,只针对英文大小写
案例:
s = 'This is a book'
a = s.upper()
b = s.lower()
print(a,b,sep="\n")
输出结果:THIS IS A BOOK
this is a book
S.strip([chars]) --> 默认去掉字符串左右的字符,默认是空格
S.strip('需要去除左右两边的字符')
案例:
s = 'This is a book'
a = s.strip("T")
b = s.strip("k")
print(a,b,sep="\n")
输出结果:his is a book
This is a boo
S.isalpha() --> 判断字符串是否全为字母,返回的是bool值,有空格也会判定false
S.isdigit() --> 判断字符串是否全为数字,返回的是bool值
S.isalnum() --> 判断字符串是否全为数字或者字母,不存在特殊字符,返回的是bool值
案例:
y = "This is a book"
e = "123456789"
s = "abced12345"
a = y.isalpha()
b = e.isdigit()
c = s.isalnum()
print(a,b,c)
输出结果:False True True
S.join(iterable) --> 将序列中的元素以指定的字符连接生成一个新的字符串
iterable #可迭代--可以将元素一个个取出
'需要连接的字符'.join(S)
案例:
y = "This is a book"
a = "-".join(y)
print(a)
输出结果:T-h-i-s- -i-s- -a- -b-o-o-k #空格也在其中