You are currently viewing Python Count Specific Character in String

How to count a specific/particular character in a string in Python? To count a specific character in a string in Python, you can use the count() method, which is available for strings. To count a specific character in a Python string, you can use various methods depending on your requirements.

Advertisements

You can count specific characters in a string using many ways, for example, by using the count(), list comprehension, for loop, reduce(), lambda, Collections.Counter(), and re.findall() functions. In this article, I will explain how to count specific characters in a string by using all these methods with examples.

Related: In Python, you can count all characters present in a string.

1. Quick Examples of Counting a Specific Character in a String

If you are in a hurry, below are some quick examples of counting a specific character in a string.


# Quick examples of counting specific characters in string

from functools import reduce
from collections import Counter
import re

# Initialize the string
string = "Welcome to sparkbyexamples"

# Example 1: Using count() method
# Count the specific characters in a string  
count = string.count('s')

# Example 2: Using list comprehension
# Count the specific characters in a string  
count = [i for i in string if i == 's']
result = len(count)

# Example 3: Using for loop
# Count the specific characters in a string  
count = 0
for char in string:
    if char == 's':
        count += 1

# Example 4: Using reduce() method
# Count the specific characters in a string  
target_character = 's' 
count = reduce(lambda acc, c: acc + 1 if c ==
               target_character else acc, string, 0)

# Example 5: Using lambda
# Count the specific characters in a string  
count = sum(map(lambda x: 1 if 's' in x else 0, string))

# Example 6: Using Collections.Counter() method
# Count the specific characters in a string  
count = Counter(string)
result = count['s']

# Example 7: Using regular expressions
# Count the specific characters in a string  
count = len(re.findall("s", string))

2. Count a Specific Character in a String Using count() Method

You can count the occurrences of a specific character in the string using the count() method. For instance, first, initialize a string variable named string with the value "Welcome to sparkbyexamples". Then you can apply this method on the string to count the occurrences of the character ‘s’. Then count is stored in the variable count. Then you print the count of occurrences of the character ‘s’ in the string.


# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using count() method
# Count the specific character in a string  
count = string.count('s')
print("Count of a specific character in a string:", count)

Yields below output.

python string count specific characters

In this case, the character ‘s’ appears twice in the string, so the count is 2.

3. Count Specific String Character Using List Comprehension

To count the occurrences of a specific character in a string using list comprehension. For instance, first, the initial string is defined as "Welcome to sparkbyexamples".

The list comprehension creates a list count that contains all occurrences of the character ‘s’ in the string. The comprehension iterates over the string and includes it in the list if it matches ‘s’. The length of the count list is calculated using the len() function. This effectively gives the count of occurrences of the character ‘s’. The result of the count is printed using the print() function.


# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using list comprehension
# Count the specific characters in a string  
count = [i for i in string if i == 's']
result = len(count)
print("Count of a specific character in a string:", result)

Yields the same output as above.

4. Python Count a Character in String using For Loop

You can use a for loop to count the occurrences of a specific character in a string. For instance, first, the initial string is defined as "Welcome to sparkbyexamples". A variable count is initialized to keep track of the count of occurrences of the target character (‘s’). A for loop iterates through each character in the string.

Inside the loop, an if condition checks whether the current character is equal to the target character (‘s’). If it is, the count variable is incremented. After the loop completes, the code prints the count of occurrences of the target character.


# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using for loop
# Count the specific characters in a string  
count = 0
for char in string:
    if char == 's':
        count += 1
print("Count of a specific character in a string:", count)

Yields the same output as above.

5. Python Count a Specific Letter in a Word Using reduce()

You can also use the reduce() function from the functools module to count the occurrences of a specific character in a string. For example, the initial string is defined as "Welcome to sparkbyexamples". The target character to count is assigned to the variable target_character. The reduce() function is used to accumulate the count of occurrences of the target character in the string. It takes three arguments, a function, an iterable (the string in this case), and an initial value for the accumulator.

The lambda function defined in your code takes two arguments, acc (the accumulator) and c (the current character from the string). It checks if the current character c is equal to the target character. If it is, it increments the accumulator (acc+1), otherwise, it leaves the accumulator unchanged (acc). The initial value for the accumulator is set to 0. After the reduce() operation is complete, the code prints the count of occurrences of the target character.


from functools import reduce

# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using reduce() method
# Count the specific characters in a string  
target_character = 's' 
count = reduce(lambda acc, c: acc + 1 if c ==
               target_character else acc, string, 0)
print("Count of a specific character in a string:", count)

Yields the same output as above.

6. Count the Specific Characters in a String Using Lambda

You can also use a combination of map(), lambda, and sum() to count the occurrences of a specific character in a string. For instance, the initial string is defined as "Welcome to sparkbyexamples". A lambda function is defined that takes an individual character x and checks if ‘s’ is in that character. If ‘s’ is present in the character, it returns 1, otherwise, it returns 0.

The map() function is used to apply the lambda function to each character in the string, resulting in a sequence of 1s and 0s. The sum() function is used, to sum up the values in the sequence, effectively counting the occurrences of the character ‘s’.


# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using lambda
# Count the specific characters in a string  
count = sum(map(lambda x: 1 if 's' in x else 0, string))
print("Count of a specific character in a string:", count)

Yields the same output as above.

7. Using Collections.Counter() Method

To count the occurrences of characters in a string, and use the Counter() function from the collections module.

In the below example, first, the collections module is imported to use the Counter class. The initial string is defined as “Welcome to sparkbyexamples”. The Counter() function is applied to the string, creating a dictionary-like object that maps each character to its count in the string. The result variable is assigned the count of occurrences of the character ‘s’ by using the dictionary-like behavior of the Counter object. The count for the specific character is printed using the print() function.


from collections import Counter

# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using Collections.Counter() method
# Count the specific characters in a string  
count = Counter(string)
result = count['s']
print("Count of a specific character in a string:",result)

Yields the same output as above.

8. Using Regular Expressions

You can also utilize the re module to count the occurrences of a specific character in a string using regular expressions. For instance, the re module is imported to use regular expression functions. The initial string is defined as "Welcome to sparkbyexamples".

The re.findall() function is used to find all occurrences of the character “s” in the string. It returns a list of all matches. The length of the list obtained from re.findall() is calculated using the len() function, giving you the count of occurrences. The count is printed using the print() function.


import re

# Initialize the string
string = "Welcome to sparkbyexamples"
print("Original string:",string)

# Using regular expressions
# Count the specific characters in a string  
count = len(re.findall("s", string))
print("Count of a specific character in a string:",count)

Yields the same output as above.

Conclusion

In this article, I have explained how to count a specific character of a string in Python by using the count(), list comprehension, for loop, reduce(), lambda, Collections.Counter(), and re.findall() functions with examples.

Happy Learning !!