Find the Length of a String Without Using len Function in Python
Last Updated :
29 Feb, 2024
In this program, we are given a string and we have to find out the length of a string without using the len() function in Python. In this article, we will see how we can find the length of a string without using len() function in Python.
Example :
Input: 'abc'
Output : 3
Explanation: Length of 'abc' is 3
Python Program to Calculate the Length of a String Without Using len() Function
Below, are the methods of counting Length Of a String Without Using Length in Python:
- Using For Loop
- Using While Loop
- Using join() Method
- Using reduce() Method
Find the Length of a String Without len() Function Using For Loop
In this example , below Python code defines a function findLen
to calculate the length of a string using a for loop and the in operator. It iterates through each character in the string, incrementing a counter for each character. Finally, the function returns the total count.
Python3
def findLen( str ):
counter = 0
for i in str :
counter + = 1
return counter
str = "geeksforgeeks"
print (findLen( str ))
|
Find the Length of a String Without len() FunctionUsing While Loop
In this example, below Python code defines a function `findLen` to calculate the length of a string using a while loop and slicing. It increments a counter while there are characters remaining in the sliced string. Finally, the function returns the total count.
Python3
def findLen( str ):
counter = 0
while str [counter:]:
counter + = 1
return counter
str = "geeksforgeeks"
print (findLen( str ))
|
Find the Length of a String Without len() FunctionUsing join() Method
In this example, below Python code defines a function `findLen` to calculate the length of a string using the `join` method and `count` method. It joins the characters of the string with a random string (‘py’ in this case) and counts the occurrences of that random string plus 1 to determine the length.
Python3
def findLen( str ):
if not str :
return 0
else :
some_random_str = 'py'
return ((some_random_str).join( str )).count(some_random_str) + 1
str = "geeks"
print (findLen( str ))
|
Find the Length of a String Without len() FunctionUsing reduce() Method
In this example, below Python code demonstrates finding the length of a string without using the built-in `len()` function. Instead, it utilizes the `reduce` method from the `functools` module. The lambda function increments the accumulator `x` for each character `y` in the string.
Python3
import functools
def findLen(string):
return functools. reduce ( lambda x, y: x + 1 , string, 0 )
string = 'geeksforgeeks'
print (findLen(string))
|
Share your thoughts in the comments
Please Login to comment...