Python中startswith()和endswith()的用法
Python中如何实现查找字符串中指定位置是否包含指定字符串?
除了常用的:
str='Hello,welcome to python world'
if 'to' in str:print(str.find('lo'))
#输出为3,即'lo'所在位置
还可以用startswith()和endswith()函数来实现:
描述
Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
通俗的讲,startswith()是判断一个字符串中是否有你要找的字符串的函数。
语法
startswith()语法:
str.startswith(str, beg=0,end=len(string));
参数:
str – 检测的字符串
strbeg – 可选参数用于设置字符串检测的起始位置。默认为0。
strend – 可选参数用于设置字符串检测的结束位置。默认到被检测字符串最后一位,或检测字符串最后一位
返回值:
如果检测到字符串则返回True,否则返回False。
实例:
endswith和startswith用法相似的,仅以startswith举例
默认起始、终止位置:
# 给定一测试字符串'Hello,welcome to python world'
str='Hello,welcome to python world'
print(str.startswith('Hell'))
#输出为:True
print(str.startswith('hell'))
#输出为:False
print(str.endswith('orld'))
#输出为:True
print(str.startswith(''))
#输出为:True,检测字符串为None的时候,均返回True
单起始位置:
print(str.startswith('o',4))
#输出为:True
print(str.endswith('orld',-5))
#输出为:True
print(str.startswith('orl',-4))
#输出为:True
print(str.startswith('orldabc',-4))
#输出为:False,检测字符串超过被检测区域,返回False
全要素使用:
print(str[1:5].startswith('ello,wel',0,6))
#输出为:False,检测超出原字符串。
print(str.startswith('ello,',1,6))
#输出为:True