Program to find the length of the given string using multiple ways in Python

Introduction

In this section, we will look forward to the number of ways to find the length of string.

Program to find the length of the given string using multiple ways 

Program

input_string = 'learning is fun , keep learning and have fun'
print("Input string is: ", input_string + "\n")


# Using len()
print("Length of string using len() :", len(input_string))


# Using loop
def str_length1(x):
    counter = 0
    for i in x:
        counter += 1
    return counter
print("Length of string using loop :", str_length1(input_string))


# Using slicing
def str_length2(i):
    counter = 0
    while i[counter:]:
        counter += 1
    return counter
print("Length of string using slicing :", str_length2(input_string))

Output

Program to find the length of the given string using multiple ways Output 

Explanation

To find the length of string we have used three ways. The first way is to use len() function. Python provides an in-built function len() to find the length of string.

The second way is by using the loop. In loop, the elements in the string are iterated over and each time the count is increased by 1. The output is returned and is printed on the screen using the print function.

The third way we used is slicing of string within the while loop. The while loop will reduce the length of string by 1 and counter is increased by 1. The reduction of length will eventually result in the empty string, and the loop will terminate. The output is returned and printed on the screen using print function.

Leave a comment

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