Open In App

Count the number of characters in a String – Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like “GeeksForGeeks”, we want to calculate how many characters it contains. Let’s explore different approaches to accomplish this.

Using len()

len() is a built-in method that returns the number of elements in a sequence, such as a string. It directly accesses the internal length attribute of the string, making it the most efficient way to count characters.

[GFGTABS]
Python

s = "GeeksForGeeks"

res = len(s)
print(res)


[/GFGTABS]

Output

13

Explanation: len() returns the length of the string (13 in this case) and assigns it to the variable res, which is then printed.

Using generator expression

Generator expression like sum(1 for _ in s) creates a lazy iterator that yields 1 for each character. The sum() function then adds these 1s, giving the total character count. This method is Pythonic, clean and allows for easy filtering to customize the counting.

[GFGTABS]
Python

s = "Geeks for Geeks!"

res = sum(1 for _ in s)
print(res)


[/GFGTABS]

Output

16

Explanation: sum(1 for _ in s) count the characters in the string s. For each character in the string, it yields 1 and the sum() function adds these 1s together.

Using for loop

This method manually loops through each character in the string, incrementing a counter by 1. It’s simple, readable and easy to modify for more complex logic like conditional counting.

[GFGTABS]
Python

s = "Geeks for Geeks!"
count = 0
for char in s:
    if char != ' ':
        count += 1

print(count)


[/GFGTABS]

Output

14

Explanation: This code initializes count to 0 and iterates over each character in s. If the character is not a space (char != ‘ ‘), count is incremented. After the loop, count contains the total number of non-space characters in the string.

Using reduce()

reduce() function from functools module applies a function cumulatively to items in a sequence. You can use it to count characters by accumulating 1 for each character, but it’s less readable and efficient than loops or built-in functions due to function call overhead.

[GFGTABS]
Python

from functools import reduce

s = "GeeksForGeeks"
res = reduce(lambda acc, _: acc + 1, s, 0)
print(res)


[/GFGTABS]

Output

13

Explanation: This code uses reduce() with a lambda function to increment an accumulator for each character in s, starting from 0. After processing all characters, it returns and prints the total count.

Related Articles:



Practice Tags :

Similar Reads