write a python program to calculate the length of a string

Hey guys in this article you will learn a python program to calculate the length of a given string.  let's ask the user to enter the string using the input function call then try to find the length of a string and print it to the standard  output.

 

write a python program to calculate the length of a string

 

 

write a python program to calculate the length of a string using built in function len()

Python Program
===================
text = input("Enter a String : ")
print(f"Length of String is : {len(text)} ")

Output
=============
Enter a String : hellow
Length of String is : 6




write a python program to calculate the length of a string Using the  for loop.

Ask the user to enter a string using the input function call and store it into a variable. Take an index variable and initialize it to zero.

Use the for loop to iterate all the letters present in the string and while the string is getting iterated increment the index by 1.

One is the for loop is completed, print the length of a string i.e, index variable.


Python program
========================
text = input("Enter a String : ")

index = 0
for _ in text:
   index += 1

print(f"Length of String is : {index} ")

Output
============
Enter a String : hey
Length of String is : 3



write a python program to calculate the length of a string using while loop

Ask the user to enter a string using the input function call and store into a variable.

Take a index variable and initialized to zero,

Use try block to catch IndexError and use while loop to iterate the letters string using the indexing. Inside the while loop keep incrementing the index variable

Use the expect block to catch the index error and pass it.

Once the while loop is completed use  the print function call to print the length of a string that is an index variable.

Python program
======================
text = input("Enter a String : ")

index = 0
try:
   while text[index]:
       index += 1
except IndexError:
   pass

print(f"Length of String is : {index} ")


Output
===========
Enter a String : code with tj
Length of String is : 12



Conclusion
===============

Above are the three methods to calculate the length of a string using built in functions, for loop and while loop.

Comment down below if you have any queries regarding the above Python program, execute the above Python program and not down the result.



Post a Comment

0 Comments