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
相关推荐
geovindu7 小时前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
寻星探路7 小时前
【JVM 终极通关指南】万字长文从底层到实战全维度深度拆解 Java 虚拟机
java·开发语言·jvm·人工智能·python·算法·ai
lbb 小魔仙7 小时前
【Java】Java 实战项目:手把手教你写一个电商订单系统
android·java·python
岱宗夫up7 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
Dxy12393102167 小时前
中文乱码恢复方案
开发语言·python
浅念-8 小时前
C/C++内存管理
c语言·开发语言·c++·经验分享·笔记·学习
No丶slovenly8 小时前
flutter笔记-输入框
前端·笔记·flutter
rongyili888 小时前
Dify 外部知识库集成 Milvus 实战指南
开发语言·python·milvus
liuchangng8 小时前
Agent Skills 核心笔记_20260212095535
笔记
Hello eveybody8 小时前
什么是动态规划(DP)?(Python版)
python·动态规划