当前位置: 首页 > 图灵资讯 > 行业资讯> python 怎么判断字符串开头

python 怎么判断字符串开头

发布时间:2025-05-09 10:56:39

函数:startswith()

功能:判断字符串是否从指定字符或子字符串开始。

python学习网,大量免费python视频教程,欢迎在线学习!

相关推荐:Python入门教程

一、函数说明

语法:string.startswith(str, beg=0,end=len(string))或string[beg:end].startswith(str)

参数说明:

string:检测到的字符串。

str:指定的字符或子字符串。(元组可使用,将逐一匹配)

beg:设置字符串检测的起始位置。(可选)

end:设置字符串检测的结束位置。(可选)

若有参数 beg 和 end,在规定范围内检查,否则在整个字符串中检查。

返回值:如果检测到字符串,返回True,否则返回False。默认空字符为True。

函数分析:如果字符串string从str开始,则返回true或False。

二、实例

>>>s='hellogoodboydoiido'
>>>prints.startswith('h')
True
>>>prints.startswith('hel')
True
>>>prints.startswith('h',4)
False
>>>prints.startswith('go',6,8)
True

#匹配空字符集
>>>prints.startswith('')
True
#匹配元组
>>>prints.startswith(('t','b','h'))
True

常用环境:用于if判断:

>>>ifs.startswith('hel'):
print"youareright"
else:
print"youarewrang"
youareright

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09