文章目录
- 索引与切片操作 Python字符串支持类似列表的索引访问,可通过整数偏移量直接获取字符或子串: sample_str = “Hello, World! This is a sample string with安hjj in it.” # 单字符访问 print(“第一个字符:”, sample_str[0]) # 输出: H print(“第五个字符:”, sample_str[4]) # 输出: o # 子串切片(左闭右开) print(“前5个字符:”, sample_str[:5]) # 输出: Hello print(“第7到12个字符:”, sample_str[7:12]) # 输出: World 操作类型 语法示例 返回值类型 边界处理 单字符 str[index] str 索引越界抛出IndexError 子串切片 str[start:end] str 超出范围自动截断 查找子串位置 使用find()方法可定位子串首次出现的位置,未找到时返回-1: target = “安hjj” index = sample_str.find(target) if index != -1: print(f”找到'{target}’,位置在:{index}”) print(“完整子串:”, sample_str[index:index+len(target)]) else: print(f”未找到'{target}'”)
- 正则表达式匹配 对于复杂模式匹配(如中文+字母组合),推荐使用re模块: import re # 匹配’安’开头后跟3个任意字符 pattern = re.compile(r’安w{3}’) match = pattern.search(sample_str) if match: print(“正则匹配结果:”, match.group()) 正则表达式常用元字符说明: 元字符 匹配规则 w 匹配字母数字及下划线 {3} 前驱元素重复3次 .* 匹配任意字符(除换行)
- # filename=”string_operations.py” def main(): sample_str = “Hello, World! This is a sample string with安hjj in it.” # 基础访问 print(“索引访问示例:”) print(“第2字符:”, sample_str[1]) # e print(“6-10字符:”, sample_str[6:10]) # , Wo # 子串查找 print(“n子串查找示例:”) target = “安hjj” pos = sample_str.find(target) if pos != -1: print(f”找到'{target}’于位置{pos}”) # 正则匹配 print(“n正则匹配示例:”) import re chinese_pattern = re.compile(r’安[a-zA-Z0-9]{3}’) result = chinese_pattern.search(sample_str) if result: print(“匹配到中文+字母组合:”, result.group()) if __name__ == “__main__”: main() 运行该程序将依次演示: 基础索引与切片操作 子串查找与位置定位 正则表达式复杂模式匹配 到此这篇关于Python判断字符串是否包含特定子串的7种方法的文章就介绍到这了,更多相关Python判断字符串是否包含特定子串内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: 使用Python算法实现从字符串中提取重复子串 python使用正则匹配判断字符串中含有某些特定子串及正则表达式详解 python七种方法判断字符串是否包含子串 python替换字符串中的子串图文步骤 在Python中实现替换字符串中的子串的示例 python实现求两个字符串的最长公共子串方法 Python字符串中查找子串小技巧
目录
- 1、使用 in 和 not in
- 2、使用 find 方法
- 3、使用 index 方法
- 4、使用 count 方法
- 5、通过魔法方法
- 6、借助 operator
- 7、使用正则匹配
- 8、知识扩展:获取特定字符与子串的完整方法
- 基础字符串访问方法
- 高级模式匹配技术
- 完整实现示例
我们经常会遇这样一个需求:判断字符串中是否包含某个关键词,也就是特定的子字符串。比如从一堆书籍名称中找出含有“python”的书名。
判断两个字符串相等很简单,直接 == 就可以了。其实判断包含子串也非常容易,而且还不止一种方法。下面我们就给大家分享 7 种可以达到此效果的方法:
in 和 not in 在 Python 中是很常用的关键字,我们将它们归类为成员运算符。
使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:
>>> "llo" in "hello, python" True >>> >>> "lol" in "hello, python" False
使用 字符串 对象的 find 方法,如果有找到子串,就可以返回指定子串在字符串中的出现位置,如果没有找到,就返回 -1
>>> "hello, python".find("llo") != -1
True
>>> "hello, python".find("lol") != -1
False
>>
字符串对象有一个 index 方法,可以返回指定子串在该字符串中第一次出现的索引,如果没有找到会抛出异常,因此使用时需要注意捕获。
def is_in(full_str, sub_str):
try:
full_str.index(sub_str)
return True
except ValueError:
return False
print(is_in("hello, python", "llo")) # True
print(is_in("hello, python", "lol")) # False
利用和 index 这种曲线救国的思路,同样我们可以使用 count 的方法来判断。
只要判断结果大于 0 就说明子串存在于字符串中。
def is_in(full_str, sub_str):
return full_str.count(sub_str) > 0
print(is_in("hello, python", "llo")) # True
print(is_in("hello, python", "lol")) # False
在第一种方法中,我们使用 in 和 not in 判断一个子串是否存在于另一个字符中,实际上当你使用 in 和 not in 时,Python 解释器会先去检查该对象是否有__contains__魔法方法。
若有就执行它,若没有,Python 就自动会迭代整个序列,只要找到了需要的一项就返回 True 。
示例如下;
>>> "hello, python".__contains__("llo")
True
>>>
>>> "hello, python".__contains__("lol")
False
>>>
这个用法与使用 in 和 not in 没有区别,但不排除有人会特意写成这样来增加代码的理解难度。
operator模块是 python 中内置的操作符函数接口,它定义了一些算术和比较内置操作的函数。operator模块是用 c 实现的,所以执行速度比 python 代码快。
在 operator 中有一个方法 contains 可以很方便地判断子串是否在字符串中。
>>> import operator
>>>
>>> operator.contains("hello, python", "llo")
True
>>> operator.contains("hello, python", "lol")
False
>>>
说到查找功能,那正则绝对可以说是专业的工具,多复杂的查找规则,都能满足你。
对于判断字符串是否存在于另一个字符串中的这个需求,使用正则简直就是大材小用。
import re
def is_in(full_str, sub_str):
if re.findall(sub_str, full_str):
return True
else:
return False
print(is_in("hello, python", "llo")) # True
print(is_in("hello, python", "lol")) # False
在Python编程中,字符串处理是基础且高频的操作。本文围绕用户提出的'获取字符串中特定字符'的需求,系统梳理了索引访问、切片操作、find()方法及正则表达式四种核心实现方案。
索引与切片操作
Python字符串支持类似列表的索引访问,可通过整数偏移量直接获取字符或子串:
sample_str = "Hello, World! This is a sample string with安hjj in it."
# 单字符访问
print("第一个字符:", sample_str[0]) # 输出: H
print("第五个字符:", sample_str[4]) # 输出: o
# 子串切片(左闭右开)
print("前5个字符:", sample_str[:5]) # 输出: Hello
print("第7到12个字符:", sample_str[7:12]) # 输出: World
| 操作类型 | 语法示例 | 返回值类型 | 边界处理 |
|---|---|---|---|
| 单字符 | str[index] | str | 索引越界抛出IndexError |
| 子串切片 | str[start:end] | str | 超出范围自动截断 |
查找子串位置
使用find()方法可定位子串首次出现的位置,未找到时返回-1:
target = "安hjj"
index = sample_str.find(target)
if index != -1:
print(f"找到'{target}',位置在:{index}")
print("完整子串:", sample_str[index:index+len(target)])
else:
print(f"未找到'{target}'")
正则表达式匹配 对于复杂模式匹配(如中文+字母组合),推荐使用re模块:
import re
# 匹配'安'开头后跟3个任意字符
pattern = re.compile(r'安w{3}')
match = pattern.search(sample_str)
if match:
print("正则匹配结果:", match.group())
正则表达式常用元字符说明:
| 元字符 | 匹配规则 |
|---|---|
w |
匹配字母数字及下划线 |
{3} |
前驱元素重复3次 |
.* |
匹配任意字符(除换行) |
# filename="string_operations.py"
def main():
sample_str = "Hello, World! This is a sample string with安hjj in it."
# 基础访问
print("索引访问示例:")
print("第2字符:", sample_str[1]) # e
print("6-10字符:", sample_str[6:10]) # , Wo
# 子串查找
print("n子串查找示例:")
target = "安hjj"
pos = sample_str.find(target)
if pos != -1:
print(f"找到'{target}'于位置{pos}")
# 正则匹配
print("n正则匹配示例:")
import re
chinese_pattern = re.compile(r'安[a-zA-Z0-9]{3}')
result = chinese_pattern.search(sample_str)
if result:
print("匹配到中文+字母组合:", result.group())
if __name__ == "__main__":
main()
运行该程序将依次演示:
- 基础索引与切片操作
- 子串查找与位置定位
- 正则表达式复杂模式匹配
到此这篇关于Python判断字符串是否包含特定子串的7种方法的文章就介绍到这了,更多相关Python判断字符串是否包含特定子串内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- 使用Python算法实现从字符串中提取重复子串
- python使用正则匹配判断字符串中含有某些特定子串及正则表达式详解
- python七种方法判断字符串是否包含子串
- python替换字符串中的子串图文步骤
- 在Python中实现替换字符串中的子串的示例
- python实现求两个字符串的最长公共子串方法
- Python字符串中查找子串小技巧