Python | String startswith()

如果字符串以给定前缀开头,startswith()方法将返回True,否则将返回False。

null

语法:

str.startswith(prefix, start, end)

参数:

prefix : prefix ix nothing but a string which needs to be checked.
start : Starting position where prefix is needs to be checked within the string.
end : Ending position where prefix is needs to be checked within the string.

注: 如果未提供开始和结束索引,则默认情况下,它将0和长度-1作为开始和结束索引,其中结束索引不包括在搜索中。

返回:

It returns True if strings starts with the given
prefix otherwise returns False.

例如:

Input : text = "geeks for geeks."
        result = text.startswith('for geeks')
Output : False

Input : text = "geeks for geeks."
        result = text.startswith('geeks', 0)
Output : True

错误: ValueError:如果在目标字符串中找不到参数字符串,则会引发此错误

# Python code shows the working of
# .startsswith() function
text = "geeks for geeks."
# returns False
result = text.startswith( 'for geeks' )
print (result)
# returns True
result = text.startswith( 'geeks' )
print (result)
# returns False
result = text.startswith( 'for geeks.' )
print (result)
# returns True
result = text.startswith( 'geeks for geeks.' )
print (result)


输出:

False
True
False
True
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享