Python String count() Method
In Python, count() is a method that can be used with both strings and lists. The string.count() function counts the number of occurrences of a substring within a string. The list.count() function counts the number of times an element appears in a list.
Here are some examples of using the count() method in Python:
To count the number of times a character appears in a string:
str = "Hello World"
x = str.count("o")
print(x)
Output: 2
To count the number of times a substring appears in a string within a specified range:
str = "Hello World"
x = str.count("l", 3, 10)
print(x)
Output: 2
To count the number of times an element appears in a tuple:
my_tuple = ("apple", "banana", "cherry", "banana")
count = my_tuple.count("banana")
print(count)
Output: 2
To count the number of times an item appears in a list:
my_list = ["a", "b", "a", "c", "a"]
count = my_list.count("a")
print(count)
Output: 3
To count the number of occurrences of different objects using a Counter object:
from collections import Counter
word = "Mississippi"
counter = Counter(word)
print(counter)
Output: Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment