Table of Contents
In this post, we will see how to count number of characters in a String in Python.
We can think of strings as a collection of characters, with every character at a given index.
Ways to count the number of characters in a string in Python
In this tutorial, we will find out the total number of characters in a string in Python.
Using the len()
function
This function is the most straightforward method. The len()
function returns the length of a given iterable in Python. We can use it to find the number of characters in a string.
For example,
1 2 3 4 |
s = 'java2blog' print(len(s)) |
Output:
Further reading:
Using the for
loop
We can use the for
loop to iterate over a string in Python. We can use a counter variable and increment it in every iteration. This variable will return the total number of characters in a string.
For example,
1 2 3 4 5 6 7 |
s = 'java2blog' t = 0 for i in s: t += 1 print(t) |
Output:
In the above example,
- The
t
variable is given a value of 0. - We iterate over the string
s
using thefor
loop. - In every iteration, we increment
t
and display its value after the loop ends.
Using the collections.Counter
class
The collections.Counter
class stores the elements of a string as key-value pairs. The keys are the characters of the string, and the value of each key is how many times this character occurs in the string.
We can sum up these values to find the total number of characters in the given string.
See the code below.
1 2 3 4 5 6 |
from collections import Counter s = 'java2blog' counter = Counter(s) print(sum(counter.values())) |
Output:
In the above code,
- We create an object of the
Counter
classob
. - We create an object of all the values of the dictionary-like object
ob
with thevalues()
function. - The
sum()
function returns the sum of these values.
Conclusion
In this tutorial, we discussed how to get the characters in a given string in Python. The len()
function is the simplest and most used method. We can also use the for
loop and Counter
class for a lengthy method.