How to use the count() method in Python? Read this article to understand

The count method is used to retrieve the number of occurrences of the specified string in another string . If the retrieved string does not exist, it returns 0, otherwise it returns the number of occurrences.
insert image description here

The syntax of the count method is as follows:

 str.count(sub[,start[,end]])
  1

In this method, the specific meaning of each parameter is as follows:

str : represents the original string;

sub : Indicates the string to be retrieved;

start : Specify the starting position of the retrieval, that is, where to start the 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 .

【Example 1】

Retrieves the number of occurrences of "." in the string "c.biancheng.net".

 >>> str = "c.biancheng.net"
  >>> str.count('.')
  2
  1
  2
  3

[Example 2]

  >>> str = "c.biancheng.net"
  >>> str.count('.',1)
  2
  >>> str.count('.',2)
  1
  1
  2
  3
  4
  5

As mentioned above, the search value corresponding to each character in the string starts from 0. Therefore, in this example, the search value 1 corresponds to the second character '.'. It can be analyzed from the output result that the search starts from the specified index position , which also contains this index location .

[Example 3]

  >>> str = "c.biancheng.net"
  >>> str.count('.',2,-3)
  1
  >>> str.count('.',2,-4)
  0

insert image description here

Guess you like

Origin blog.csdn.net/Z987421/article/details/132587266