In this article we will see Python programs to find the length of a String.
1. Python program to calculate length of a String without using len() function
First we will see how to find the length of string without using library function len(). Here we are taking the input from user and counting the number of characters in the input string using for loop.
# User inputs the string and it gets stored in variable str str = input("Enter a string: ") # counter variable to count the character in a string counter = 0 for s in str: counter = counter+1 print("Length of the input string is:", counter)
Output:
Enter a string: Beginnersbook Length of the input string is: 13
2. Program to find the length of string using library function
In the above program we have not used the library function to find length, however we can do the same thing by using a built-in function. The function len() returns the length of a given string. Lets have a look at the following code:
# User inputs the string and it gets stored in variable str str = input("Enter a string: ") # using len() function to find length of str print("Length of the input string is:", len(str))
Output:
Enter a string: Chaitanya Length of the input string is: 9
Leave a Reply