在 Python 中检查字符串中是否存在子字符串

pythonserver side programmingprogramming更新于 2025/12/27 8:44:17

在 Python 数据分析中,我们可能会遇到一种情况,即检查给定的子字符串是否是更大字符串的一部分。我们将通过以下程序实现此目的。

使用 find

find 函数查找指定值的第一次出现。如果未找到该值,则返回 -1。我们将此函数应用于给定的字符串,并设计一个 if 子句来找出子字符串是否是字符串的一部分。

示例

Astring = "In cloud 9"
Asub_str = "cloud"
# 给定字符串和子字符串
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

# 再次检查
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

输出

运行上述代码得到以下结果 −

Given string: In cloud 9
Given substring: cloud
Substring is part of the string
Given substring: 19
Substring is not a part of the string

使用 count

方法 count() 返回 Python 中字符串或数据集合中具有指定值的元素数量。在下面的程序中,我们将计算子字符串的数量,如果数量大于 0,则我们得出结论,子字符串存在于更大的字符串中。

示例

Astring = "In cloud 9"
Asub_str = "cloud"
# 给定字符串和子字符串
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is part of the string")
else:
   print("Substring is not a part of the string")

# 再次检查
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is a part of the string")
else:
   print("Substring is not a part of the string")

输出

运行上述代码得到以下结果 −

Given string: In cloud 9
Given substring: cloud
Substring is not a part of the string
Given substring: 19
Substring is not a part of the string

相关文章


有用资源