Python find length of string; Through this tutorial, i am going to show you how to find string length in Python with and without using the built-in method/function.
In this tutorial, i will write some python programs to calculate or find length of a string with and without using len() function.
How to Find Length Of String in Python
There are two way to find length of string in python; as shown below:
- 1: How to find length of string in python using len
- 2: Find string length in python using while loop and slicing
- 3: Get/Find string length in python using For loop and operator
- 4: Calculate length of a string without using len() function with join() and Count
1: How to find length of string in python using len
See the following python program to find length of string with using built in function len() function:
# python program to find string length # using len str = "hello" print(len(str))
Output
5
2: Find string length in python using while loop and slicing
See the following python program to find length of string without using while loop:
# program to find length of string in python # using while loop. # Returns length of string def getLen(str): counter = 0 while str[counter:]: counter += 1 return counter str = "Hello" print(getLen(str))
Output
5
3: Get/Find string length in python using For loop and operator
Using python for loop and in operator to find the length of Python string; as shown below in python program:
# program to find length of string in python # using for loop # Returns length of string def getLen(str): counter = 0 for i in str: counter += 1 return counter str = "Hello" print(getLen(str))
Output
5
4: Calculate length of a string without using len() function with join() and Count
Using python string methods join and count to calculate length of a string without using len() function; as shown below python program:
# program to find length of string in python # using join and count # Returns length of string def getLen(str): if not str: return 0 else: some_random_str = 'py' return ((some_random_str).join(str)).count(some_random_str) + 1 str = "hello" print(getLen(str))
Output
5