检查子字符串在Python中是否存在
在python数据分析中,我们可能会遇到一种情况,以检查给定的子字符串是否是较大字符串的一部分。我们将通过以下程序实现这一目标。
与查找
查找功能查找指定值的第一次出现。如果找不到该值,则返回-1。我们将把这个函数应用于给定的字符串,并设计一个if子句来找出子字符串是否是字符串的一部分。
示例
Astring = "In cloud 9" Asub_str = "cloud" # Given string and substring 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") # Check Agian 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()
在python的字符串或数据集合中返回具有指定值的元素数。在下面的程序中,我们将计算子字符串的计数,如果它大于0,我们得出结论,子字符串存在于较大的字符串中。
示例
Astring = "In cloud 9" Asub_str = "cloud" # Given string and substring 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") # Check Agian 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