Python3 笔记:字符串的 startswith() 和 endswith()

1、startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定了值,则在指定范围内检查。

语法:str.startswith(substr, beg=0,end=len(string))

参数:

str -- 检测的字符串。

substr -- 指定的子字符串。

strbeg -- 可选参数用于设置字符串检测的起始位置。

strend -- 可选参数用于设置字符串检测的结束位置。

python 复制代码
str1 = 'this is a test'
print(str1.startswith('this'))	# 运行结果:True
print(str1.startswith('this',2))	# 运行结果:False
print(str1.startswith('this',0,6))	# 运行结果:True

2、endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。

语法:str.endswith(suffix, start\[, end])

参数

suffix -- 该参数可以是一个字符串或者是一个元素。

start -- 字符串中的开始位置。

end -- 字符中结束位置。

python 复制代码
str1 = 'this is a test'
print(str1.endswith('this'))	# 运行结果:False
print(str1.endswith('test',2))	# 运行结果:True
print(str1.endswith('this',0,9))	# 运行结果:False
print(str1.endswith('this',0,4))	# 运行结果:True
相关推荐
嘘嘘出差1 天前
Python 爬虫入门实战:爬取豆瓣电影 Top 250
开发语言·爬虫·python
爱写代码的倒霉蛋1 天前
实现协程的三种方式
开发语言·python
崖边看雾1 天前
记录Python学习——第一章环境安装下载(Windows)
windows·python·学习·pycharm
用户298698530141 天前
Python 实现 Excel 到 ODS、XPS、PostScript 及 PDF/A-1b 的格式转换
后端·python·excel
本地化文档1 天前
xlwings-docs-l10n
python·github·excel·gitcode·sphinx
梅雅达编程笔记1 天前
零基础学 Python 第7章 | 字典 dict:键值对存储
开发语言·python·beautifulsoup·numpy·pandas
heroboyluck1 天前
AI工程师第四课 - 深度学习入门
人工智能·python·深度学习·llama
alicema11111 天前
BRAIN 研究顾问(Research Consultant)兼职
python·量化
元Y亨H1 天前
Python,单引号和双引号有何区别
python