在Python中,检查一个字符串是否包含另一个子字符串可以使用以下方法:
-
使用
in
关键字:string1 = "Hello, World!" substring = "World" if substring in string1: print("Substring found") else: print("Substring not found")
-
使用
str.find()
或str.index()
方法:find()
方法会返回子字符串在原始字符串中的起始位置(索引),如果找不到则返回-1
。
string1 = "Hello, World!" substring = "World" index = string1.find(substring) if index != -1: print("Substring found at index", index) else: print("Substring not found")
index()
方法和find()
类似,但当找不到子字符串时,它会抛出一个异常(ValueError
)。
-
如果需要进行大小写不敏感的搜索,可以在比较前将字符串转换为统一的大小写形式:
string1 = "Hello, World!" substring = "world" if substring.lower() in string1.lower(): print("Substring found (case insensitive)") else: print("Substring not found (case insensitive)")
以上代码片段演示了如何在Python中检查一个字符串是否包含特定的子字符串。