在 Python 中检查字符串中是否存在子字符串
在 Python 数据分析中,我们可能会遇到需要检查给定子字符串是否为更大字符串的一部分的情况。我们将通过以下程序实现这一目标。
使用 find 方法
find 函数查找指定值的第一次出现。如果未找到该值,则返回 -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 方法
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP