Skip to content

Python count characters in string

  • by

Use the len() method to count characters in a string in Python. This is the most convenient method in Python to get the occurrence of any element in any container.

Python counts characters in a string

Simple example code.

# define string
s = "Python is awesome, isn't it?"

# print count
print("The count is:", len(s))


Python count characters in string

The following code replaces any nun-numeric character with ”, allowing you to count several such characters with function len.

import re
len(re.sub("[^0-9]", "", my_string))


import re
len(re.sub("[^a-zA-Z]", "", my_string))

As for counting characters in a string, use the count() method:

 s = "Green tree"
 print(s.count("e")) #4

Find the count of characters within the string in Python

The ideal way to do this is by using collections.Counter:

>>> from collections import Counter
>>> str1 = "aabbaba"
>>> Counter(str1)
Counter({'a': 4, 'b': 3})

Do comment if you have any doubts or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading