一、startswith()函数:
描述:
startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
方法语法:
str.startswith(str, beg=0,end=len(string));
案例:
1、省略范围
word = 'alhdjaldhffNB'
if word.startswith('al') :
print('是的')
else:
print('不是的')
#输出结果:是的
2、增加范围
以下,给到的检查范围内的字符串是以‘al’字符开头:
word = 'alalhdjhddhlllNB'
if word.startswith('al',2,5) :
print('是以al开头的')
else:
print('不是以al开头的')
#输出结果:是以al开头的
以下,给到的检查范围内的字符串不是以‘al’字符开头,但包含‘al’字符:
word = 'alhdjhallddhlllNB'
if word.startswith('al',2,len(word)-1) :
print('是以al开头的')
else:
print('不是以al开头的')
#输出结果:不是以al开头的
二、endswith()函数:
描述:
endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。
方法语法:
str.endswith(suffix, start, end)
suffix参数可以是一个字符串或者一个元素
start 参数为开始范围,以 0 为第一个字符索引值。
end 参数为结束范围,以 1 为第一个字符索引值。
案例:
1、省略范围
word = 'ashakdkNB'
print(word.endswith('NB')
#输出结果:True
2、增加范围
word = 'ashakdkNB'
print(word.endswith('NB',2,len(word)))
#输出结果: True
范围值仅填写一个数字,代表从0开始2的索引位置往后的字符串的末尾是否以NB结尾:
word = 'ashakdkNB'
print(word.endswith('NB',2))
#输出结果: True
索引位置之后不是以NB结尾,则输出false:
word = 'ashakdkNB'
print(word.endswith('NB',8))
#输出结果: False
三、str replace方法
方法描述:
replace() 方法把字符串中的 old_str 替换成 new_str,如果指定第三个参数max,则替换不超过 max 次。
方法语法:
str.replace(old_str,new_str,max)
案例:
1、不填写Max
#将name变量对应的值中的所有’l‘替换为’p‘,并输出结果
name = 'ajkkslllshsllshhs'
name = name.replace('l','p')
print(name)
结果输出:
before: ajkkslllshsllshhs
after: ajkkspppshsppshhs
2、填写Max
#将name变量对应的值中的所有’l‘替换为’p‘,并输出结果
name = 'ajkkslllshsllshhs'
name = name.replace('l','p',2)
print(name) #输出'ajkkspplshsllshhs'
结果输出:
before: ajkkslllshsllshhs
after: ajkkspplshsllshhs
3、特殊情况
1)替换次数为负数/0
当替换次数Max为负数/0时,不进行任何的替换,此时替换次数是不生效的
name = 'llhdjhddhlll'
name = name.replace('l','6',-1)
print(name)
结果输出:
before: llhdjhddhlll
after: llhdjhddhlll
2)替换次数大于需替换字符的个数
当替换次数大于需替换字符的个数时,则按照次数从左至右进行替换,字符替换完成后,仍有次数,则忽略;
name = 'llhdjhddhlll'
name = name.replace('l','6',6)
print(name)
结果输出:
before: llhdjhddhlll
after: 66hdjhddh666
3)old_str不存在
old_str不存在时,无论new_str是什么,替换次数时多少,皆不进行任何的替换,因为……找不到
name = 'llhdjhddhlll'
name = name.replace('a','6',1)
print(name)
结果输出:
before: llhdjhddhlll
after: llhdjhddhlll
4)new_str为空
当new_str为空时,仍会进行替换,会以空字符串替换old_str
name = 'llhdjhddhlll'
name = name.replace('ll','',1)
print(name)
结果输出:
before: llhdjhddhlll
after: hdjhddhlll