In the interview it can be a question- How can I get the length of a string without using the len() function or any string methods. Without the len() method you can get the length of string using a for-loop, while-loop, join function.
Click to see an example of len function and questions – Python string count function
Ways to string length count in Python
- Using for loop and in operator
- Using while loop and Slicing
- Using string methods join and count
A simple method will work this all
- Take input and pass into a function (A function which counts the lengths)
- Initialize a count variable to 0.
- Run a loop till length and increment count by 1.
- On complete loop return count.
Let’s see the examples
We will make write our own Python string length count function as mentioned above ways.
1. for loop and in operator
You can get the length of the string with a for
loop.
def findLen(str_value): count = 0 for i in str_value: count += 1 return count str1 = "EyeHunts" print(findLen(str1))
Output: 8
2. while loop and Slicing
Using while loop.
def findLen(str_value): count = 0 while str_value[count:]: count += 1 return count str1 = "EyeHunts sting Length" print(findLen(str1))
Output: 21
3. string methods join and count.
def findLen(str_value): if not str_value: return 0 else: random = 'py' return ((random).join(str_value)).count(random) + 1 str1 = "Python String length without len function" print(findLen(str1))
Output: 41
Do comment if you have any doubts and suggestions on this article. If you know any other way to do it, do write an example in a comment.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.