欢迎访问宙启技术站
智能推送

使用Python的count()函数计算字符串中出现次数

发布时间:2023-06-30 21:44:26

要使用Python的count()函数来计算字符串中出现某个子字符串的次数,你需要提供一个要计算的子字符串,然后调用count()函数来对字符串进行计数。以下是一个示例代码:

def count_substring(string, substring):
    count = string.count(substring)
    return count

# 测试示例
string = "This is a test string. This string contains multiple occurrences of the word string."
substring = "string"
result = count_substring(string, substring)
print(f"The substring '{substring}' appears {result} times in the string.")

执行上述代码将输出:

The substring 'string' appears 3 times in the string.

在这个例子中,我们定义了一个名为count_substring的函数,它接受两个参数:string是要搜索的源字符串,substring是要计数的子字符串。函数内部使用count()函数计算子字符串在原字符串中的出现次数,并将结果返回。

然后,我们在示例测试中定义了一个字符串和一个子字符串,并通过调用count_substring函数来计算子字符串在原字符串中的出现次数。最后,我们将结果打印出来。