[Self-study Python] The number of occurrences of Python strings

Python string occurrence count

Python String Occurrences Tutorial

In the development process, we often need to count the number of occurrences of a single character or string in another string. In Python , we use the count() function to count the number of occurrences of a string.

Detailed explanation of Python count() function

grammar

S.count(sub[, start[, end]]) -> int

parameter

parameter describe
S Represents the original string.
sub Indicates the string to retrieve.
start Specify the starting position of the search, that is, where to start detection. If not specified, the search starts from the beginning by default.
end Specify the end position of the search, if not specified, it means to search all the way to the end.

return value

The count() function returns a value of type int , and returns 0 if the retrieved string does not exist, otherwise returns the number of occurrences.

the case

number of occurrences of a single character

Use the count() function to count the number of occurrences of a single character in a string

print("嗨客网(www.haicoder.net)")

# 使用 count() 函数,统计字符串中单个字符出现的次数
strHaicoder = "Study Python From HaiCoder"
print(strHaicoder.count('o'))

After the program runs, the console output is as follows:

Please add a picture description

First, we define a variable strHaicoder of string type, then we use the count() function of the string to count the number of occurrences of a single character in the string variable strHaicoder o, and use the print() function to print the final result.

The character oappears three times in the variable strHaicoder, so 3 is finally printed.

string occurrences

Use the count() function to count the number of occurrences of a specified string in a string

print("嗨客网(www.haicoder.net)")

# 使用 count() 函数,统计字符串中指定字符串出现的次数
strHaicoder = "I love Python and I study Python From HaiCoder"
print(strHaicoder.count('Python'))

After the program runs, the console output is as follows:

Please add a picture description

First, we define a variable strHaicoder of string type, then we use the count() function of the string to count the number of occurrences of the string in the string variable strHaicoder Python, and use the print() function to print the final result.

The string Pythonappears twice in the variable strHaicoder, so 2 is finally printed.

Summary of occurrences of Python strings

In the development process, we often need to count the number of occurrences of a single character or string in another string. In Python, we use the count() function to count the number of occurrences of a string. Python count() function syntax:

S.count(sub[, start[, end]]) -> int

Guess you like

Origin blog.csdn.net/weixin_41384860/article/details/128700386