📅  最后修改于: 2023-12-03 15:19:10.632000             🧑  作者: Mango
在 Python 中,我们可以使用 in
关键字来检查一个字符串中是否包含某个字符。
string = "hello world"
if "h" in string:
print("h found in string")
else:
print("h not found in string")
以上代码将输出 h found in string
,因为字符串 "hello world"
中包含字符 "h"
。
如果要忽略大小写,可以将字符串转换为小写或大写,然后检查字符是否存在:
string = "Hello World"
if "h" in string.lower():
print("h found in string")
else:
print("h not found in string")
以上代码也将输出 h found in string
,因为 string.lower()
将字符串转换为小写,然后检查小写字符串中是否包含 "h"
。
如果要检查字符串中是否存在多个字符,可以使用循环遍历每个字符:
string = "hello world"
for char in ["h", "w", "z"]:
if char in string:
print(char + " found in string")
else:
print(char + " not found in string")
以上代码将输出以下内容:
h found in string
w found in string
z not found in string
希望这篇文章对你有帮助!