一文搞懂Python中的in运算符

自由坦荡的智能 2025-04-09 22:14:30

什么是in运算符?

在Python中,使用 in 运算符来检查字符串中是否存在子字符串。语法很简单:

substring in string

这里, substring 是您要搜索的文本, string 是您要在其中搜索的字符串。 in 运算符根据是否找到子字符串返回布尔值( True 或 False )。

基本用法

从一个基本示例开始来说明 like 运算符的用法:

text = "Python is a versatile programming language."substring = "versatile"if substring in text: print("Found the substring!")else: print("Substring not found.")

在此代码片段中,我们检查 substring “versatile” 是否存在于 text 变量中。既然如此,程序将输出“Found the substring!”。

区分大小写

默认情况下, in 运算符区分大小写。这意味着它只会匹配与正在搜索的字符串具有相同大小写的子字符串。要执行不区分大小写的搜索,可以在应用 in 运算符之前将子字符串和字符串都转换为小写(或大写):

text = "Python is a versatile programming language."substring = "Versatile"if substring.lower() in text.lower(): print("Found the substring (case-insensitive)!")else: print("Substring not found (case-insensitive).")

通过将 substring 和 text 都转换为小写,我们确保搜索不区分大小写,从而使我们能够找到“Versatile”,即使它的大小写不同。

多个子串

可以使用 in 运算符通过循环或列表推导来搜索多个子字符串。例如:

text = "Python is a versatile programming language."substrings = ["Python", "versatile", "programming"]found_substrings = [substring for substring in substrings if substring in text]print("Found substrings:", found_substrings)

在此示例中,有一个子字符串列表,使用列表理解来查找 text 变量中存在的所有子字符串。

使用not in运算符

相反,也可以使用 not in 运算符来检查字符串中是否不存在子字符串:

text = "Python is a versatile programming language."substring = "Java"if substring not in text: print("Substring not found.")else: print("Found the substring!")

在这种情况下,程序将输出“Substring not find”,因为 text 变量中不存在“Java”。

0 阅读:0

自由坦荡的智能

简介:感谢大家的关注