如何使用Python的count()函数检查子字符串是否在字符串中出现
要检查一个子字符串是否在一个字符串中出现,可以使用count()函数来计算子字符串在字符串中出现的次数。如果子字符串出现的次数大于0,那么它就在字符串中出现过。
以下是一个示例,演示如何使用count()函数来检查一个子字符串是否在一个字符串中出现:
# 检查一个子字符串是否在一个字符串中出现 text = "pidancode is a great website for learning Python programming" substring = "Python" if text.count(substring) > 0: print(f"{substring} is in the text.") else: print(f"{substring} is not in the text.")
输出结果:
Python is in the text.
在上述示例中,我们使用count()函数计算字符串text中子字符串substring出现的次数。如果次数大于0,就说明子字符串在字符串中出现过。因此,我们输出一条包含子字符串的信息。如果次数等于0,则输出一条不包含子字符串的信息。
再举一个使用网址的示例:
# 检查一个子字符串是否在一个字符串中出现 url = "https://pidancode.com/" substring = "pidancode" if url.count(substring) > 0: print(f"{substring} is in the url.") else: print(f"{substring} is not in the url.")
输出结果:
pidancode is in the url.
在上述示例中,我们使用count()函数计算字符串url中子字符串substring出现的次数。如果次数大于0,就说明子字符串在字符串中出现过。因此,我们输出一条包含子字符串的信息。如果次数等于0,则输出一条不包含子字符串的信息。
相关文章