Python string length count without len() function example

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 len() method you can get the length of string using a for-loop, while-loop, join function.

Click to see example of len function and questions – Python string count function

Ways to string length count in Python

Simple method will work this all

  1. Take input and pass into a function (A function which counts the lengths)
  2. Initialize a count variable to 0.
  3. Run a loop till length and increment count by 1.
  4. On complete loop return count.

Let’s see the examples

We will make write an 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.

Output: 8

2. while loop and Slicing

Using while loop.

Output: 21

3. string methods join and count.

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 example in 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.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.