Python program to count the number of characters in a String
Last Updated :
07 Jan, 2025
Improve
In this article, we will see the program to count the number of characters in a String. In Python, the len()
function is used to determine the length of an object.
Example:
s = "Geeks for Geeks!"
# Count the characters using len() function
count = len(s)
print(count)
Output
16
Explanation
- The string
s
is initialized with the value"Geeks for Geeks!"
. - The
len()
function is used to count the number of characters in the string, and the result is printed with the message"Number of characters:"
.
Using a for
loop:
A for
loop in Python allows you to iterate through each character in a string or element in an iterable. This method can be used to count characters by incrementing a counter during each iteration.
s = "GeeksforGeeks"
# Initialize count variable
count = 0
# Iterate through each character in the string
for char in s:
count += 1
print(count)
Output
13
Explanation:
- The string
s
is initialized with the value"GeeksforGeeks"
. - A variable
count
is set to 0 to keep track of the number of characters. - A
for
loop iterates over each character in the string, and for each character, thecount
is incremented by 1. Finally, the total count is printed.
Using join()
and map()
:
join()
method combines elements of an iterable into a string, while map()
applies a function to each element. Together, they provide an efficient way to process and concatenate items in a single operation.
# Define the input string
s = "GeeksForGeeks"
# Use map() to create an iterable of characters and join them to count
count = len(''.join(map(str, s)))
print(count)
Output
13
Explanation
- The string
s
is initialized with the value"GeeksForGeeks"
. - The
map()
function converts each character of the string into a string (if needed), andjoin()
concatenates them into a single string. - The
len()
function is used to count the total number of characters in the concatenated string, and the result is printed.