如何使用Python的count()函数检查多个子字符串在一个字符串中出现的次数
要检查多个子字符串在一个字符串中出现的次数,可以在循环中依次计算每个子字符串在字符串中出现的次数,并将这些次数加起来。
以下是一个示例,演示如何使用count()函数来检查多个子字符串在一个字符串中出现的次数:
# 检查多个子字符串在一个字符串中出现的次数 text = "pidancode is a great website for learning Python programming" substrings = ["Python", "programming"] count = 0 for substring in substrings: count += text.count(substring) print(f"The total count of substrings is {count}.")
输出结果:
The total count of substrings is 2.
在上述示例中,我们首先定义一个包含多个子字符串的列表substrings,并定义一个变量count来保存出现次数。然后,在循环中,我们遍历每个子字符串,并使用count()函数来计算它在字符串text中出现的次数。每次循环结束后,我们将这个次数加到count变量中。最终,我们输出总的出现次数。
再举一个使用网址的示例:
# 检查多个子字符串在一个字符串中出现的次数 url = "https://pidancode.com/" substrings = ["http", "pidancode"] count = 0 for substring in substrings: count += url.count(substring) print(f"The total count of substrings is {count}.")
输出结果:
The total count of substrings is 2.
在上述示例中,我们使用与之前示例相同的方法来检查多个子字符串在字符串url中出现的次数。最终,我们输出总的出现次数。
相关文章