Python Program to Find Length of String

In this article, I've created some programs in Python, that find and prints length of string entered by user. Here are the list of approaches used:

Find Length of String using for Loop

To find length of any string in Python, you have to ask from user to enter any string and then find its length in character-by-character manner, using for loop, like shown in the program given below:

print("Enter the String: ")
text = input()

tot = 0
for ch in text:
    tot = tot+1

print("\nLength =", tot)

Here is its sample run:

find length of string python

Now supply the input say fresherearth as string and press ENTER key to find and print length of given string using for loop:

length of string program python

When user enters a string say fresherearth, then it gets stored in a variable named text. Now using for loop, the dry run of above program goes like:

Find Length of String using while Loop

The question is, write a Python program to find length of a given string using while loop. Here is its answer:

print("Enter a String: ", end="")
text = input()

tot = 0
while text[tot:]:
    tot = tot+1

print("\nLength =", tot)

Here is its sample run with string input welcome to jobails.com:

python find length of string

While slicing the string, the [tot:] refers to all characters from index number tot to last. For example if text = "fresherearth" is a given string. Therefore at 0th index of text (text[0]), 'c' is available, at 1st index of text (text[1]), 'o' is available, and so on. So if tot=2, then text[2:] returns "descracker" (all characters from second index).

Find Length of String using len()

This program is created using a predefined function named len(), that returns length of an object passed as its argument.

print("Enter a String: ", end="")
text = input()

textlen = len(text)
print("\nLength =", textlen)

Find Length of String using Function

This is the final program on finding length of a given string in Python, created using a user-defined function named FindLenOfStr(). It returns the length of a value passed as its argument.

def FindLenOfStr(x):
    return len(x)

print("Enter a String: ", end="")
text = input()

print("\nLength =", FindLenOfStr(text))

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »