Count of Characters in Python String

Suppose you have a string and wants to count characters in string then how you can do so. In this tutorial you will learn the different ways to count characters in string in python.

How to count each character in string python

To count each character in string in python follow the below steps.

Step 1: Initialize a sample dictionary

char_count = {}

It will hold the count for each of the character in the string.

Step 2:  Define the loop.

for char in string:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1

Loop will take each character in the string and increment the count and append to the dictionary.

Full Code

string = "Code the best !"
char_count = {}

for char in string:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1

print(char_count)

Output

{'C': 1, 'o': 1, 'd': 1, 'e': 3, ' ': 3, 't': 2, 'h': 1, 'b': 1, 's': 1, '!': 1}

Count of characters in a string python

To count the number of characters in a string you will use the length function that is len().

string = "Code the best !"
char_count = len(string)
print(char_count)

Output

15

The len() function also includes space and punctuation. If you don’t want to include it then you can use the string module and a loop to iterate over the characters in the string and count only the alphanumeric characters.

import string

string = "Code the best !"
char_count = 0

for char in string:
    if char in string.ascii_letters + string.digits:
        char_count += 1

print(char_count)

Output

10

Count number of special characters in a string

You can use the string module  to count the number of special characters in a string. You will use the loop to iterate over each character and count only non alphanumeric character.

Execute the below lines of code and see the output.

import string

string = "Code the best !"
special_count = 0

for char in string:
    if char not in string.ascii_letters + string.digits + string.whitespace:
        special_count += 1

print(special_count)

Output

1

Conclusion

In this  tutorial you have learner the following things.

  • How to count number of each charters in a string.
  • Finding the length of a string with and without space and punctuation
  • Counting the number of special characters in string.

 

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link