在Python中,与str.endswith()类似的方法(主要涉及字符串的开头/结尾检查、子串搜索等)有很多,以下是核心方法及其功能对比:
1. 开头检查:str.startswith()
- 功能:检查字符串是否以指定前缀开头,返回
True/False。 - 示例:
"hello.txt".startswith("hello") # True "hello.txt".startswith(("hello", "test")) # 可接受元组,检查多个前缀
2. 子串搜索:str.find() / str.index()
str.find(sub):返回子串sub首次出现的索引,不存在时返回-1。str.index(sub):返回子串sub首次出现的索引,不存在时抛出ValueError。- 示例:
"apple".find("p") # 1 "apple".index("z") # 抛出 ValueError
3. 反向搜索:str.rfind() / str.rindex()
- 功能:从右向左搜索子串的位置(
rfind返回-1,rindex抛出异常)。 - 示例:
"banana".rfind("a") # 5
4. 分割与分区:str.split() / str.partition()
str.split(sep):按分隔符分割字符串,返回列表。str.partition(sep):将字符串分割为三部分(前缀、分隔符、后缀),返回元组。- 示例:
"a,b,c".split(",") # ['a', 'b', 'c'] "hello world".partition(" ") # ('hello', ' ', 'world')
5. 替换:str.replace()
- 功能:替换子串,可指定替换次数。
- 示例:
"hi world".replace("hi", "hello", 1) # "hello world"
6. 空白处理:str.strip() / str.lstrip() / str.rstrip()
- 功能:移除字符串开头/结尾/两端的空白字符(或指定字符)。
- 示例:
" text ".strip() # "text" "www.example.com".lstrip("w") # ".example.com"
7. 大小写转换:str.lower() / str.upper() / str.capitalize()
- 功能:转换字符串的大小写格式。
8. 格式检查:str.is... 系列
- 如
isdigit()、isalpha()、isalnum()等,用于检查字符串的组成(数字、字母等)。
9. 正则匹配:re.match() / re.search()
- 需导入
re模块,支持复杂模式匹配(如开头/结尾的正则表达式)。 - 示例:
import re re.match(r"^hello", "hello world") # 匹配开头
关键区别总结
| 方法 | 方向 | 返回值类型 | 异常情况 |
|---|---|---|---|
str.endswith() |
结尾 | bool |
无 |
str.startswith() |
开头 | bool |
无 |
str.find() |
任意方向 | int(索引) |
不存在时返回-1 |
str.index() |
任意方向 | int(索引) |
不存在时抛出异常 |
str.partition() |
任意方向 | tuple(三部分) |
无 |
这些方法覆盖了字符串操作的常见需求,可根据具体场景(如精确匹配、模糊搜索、格式验证等)选择合适的方法。
