Python字符串count()
时间:2020-02-23 14:43:24 来源:igfitidea点击:
Python String count()函数返回给定字符串中子字符串出现的次数。
Python字符串count()
count()函数的语法为:
str.count(sub[, start[, end]])
sub是在给定字符串中找到的子字符串。
start是一个可选参数。
它指定从中查找子字符串的起始索引位置。
默认值为0。
end是一个可选参数。
它指定指定字符串中的结束索引位置。
它的默认值是字符串的长度。
让我们看一个简单的字符串count()函数示例。
s = 'I like Python programming. Python is Awesome!' print(f'Number of occurrence of "Python" in String = {s.count("Python")}') print(f'Number of occurrence of "Python" in String between index 0 to 20 = {s.count("Python", 0, 20)}')
输出:
Number of occurrence of "Python" in String = 2 Number of occurrence of "Python" in String between index 0 to 20 = 1
推荐读物:Python f字符串
让我们看另一个示例,在该示例中,用户将输入字符串和子字符串,我们将使用count()函数来打印出现次数。
s = input('Please enter a string:\n') sub = input('Please enter a sub-string:\n') print(f'Number of occurrence of "{sub}" in the "{s}" is {s.count(sub)}')
输出:
Please enter a string: a,e,i,o,u Please enter a sub-string: , Number of occurrence of "," in the "a,e,i,o,u" is 4 Please enter a string: Hello World from Python Tutorials from theitroad Please enter a sub-string: from Number of occurrence of "from" in the "Hello World from Python Tutorials from theitroad" is 2