字符切片
str[n1:n2:n3]
表示按步长为n3(每隔一定长度取字符),从标号为n1,到n2-1取字符(注意范围是左闭右开)。
例子:
str='Runoob'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到最后一个所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始后的所有字符
print(str[1:5:2]) # 输出从第二个开始到第五个且每隔两个的字符
print(str[::-1])#非常常用要注意,截取与原来字符串顺序相反的字符串
print(str[:-5:-3])#从—1开始逆向截取,隔三个字符到-5,步长的符号体现截取顺序
结果:
Runoob
Runoo
R
noo
noob
uo
boonuR
bn
定位字符数据
str1.find(str,beg,end):
该方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始
str1.index(str,beg,end):
该方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始标号) 和 end(结束标号) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
例子:
mystr='hello world and hello my life' #空格也算字符串一部分
str01=mystr.find('life')
print(str01)
str02=mystr.find('hehe')
print(str02)
str03=mystr.find('life',0,10)
print(str03)
str04=mystr.index('life',0,10)
print(str04)
结果:
25
-1
-1
Traceback (most recent call last):
File "D:\PyCharm work\基础\05-字符串.py", line 27, in <module>
str04=mystr.index('life',0,10)
ValueError: substring not found
进程已结束,退出代码为 1
str1.count(str):
查找部分切片出现次数
str.replace(old, new, max):
切片替换方法,不能改变原字符串,只能替换以后将字符串给一个新的变量,把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str1.split(str,num) :
通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串,返回的字符串存放在列表中,如果切片的分隔符为空则默认使用空格来切片
例子:
mystr='hello world and hello my life'
count01=mystr.count('o')
print(count01)
count02=mystr.count("hello")
print(count02)
rep03=mystr.replace('hello','haha')
print(rep03)
rep04=mystr.replace('hello','haha',1)
print(rep04)
time='2021-08-14'
list01=time.split('-')
print(list01)
list02=mystr.split()
print(list02)
结果:
3
2
haha world and haha my life
haha world and hello my life
['2021', '08', '14']
['hello', 'world', 'and', 'hello', 'my', 'life']