Python Program to find the length of a string
Python program to find the length of a string
A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters in a string is known as the length of the string. In this article, we'll look at the various methods for determining the length of a string.
Example: Input = “ABC” Output = 3 Input = “Hello” Output = 5
Method 1: Using built-in method len()
The built-in len() method is the simplest way to calculate a string's length in Python. It takes a string as a parameter and returns the length of that string as an integer.
The following source code calculates the length of a string with the use of library functions.
#Program to find the length of a string using len() #input string str = input("Enter a string: ") #prints the result print(len(str))
Explanation: A built-in function len() returns the number of characters in a string.
Method 2: Using for loop
The following source takes the input string from the user and counts the number of characters in the input string using for loop.
#Program to find length of a string with for loop #input string str = input("Enter a string: ") #returns length of string def length(str): count = 0 for i in str: temp += 1 return count #prints the result print("Length of the input string is:",len(str))
Explanation: In the above code, we have declared a length() and pass the argument str. We have used the variable temp in for loop to store the number of iterations of string. When the iteration completes, the length of the string will be printed on the screen.
Method 3: Using while loop and slicing
The following source code counts each character's position in the string by using the string slicing method. The string's length is determined by the final count of the number of positions in the string.
#Program to find length of string using slicing approach #return string length def length(String1): count = 0 while String1[count:]: count += 1 return count #Input string String1 = "TUTORIALANDEXAMPLE" #prints the result print("Length of the input string is:",len(String1))
Explanation: Each iteration of slicing a string shorter by one would probably result in an empty string. This is where the while loop comes to an end. The length of the string can be calculated by keeping the count of the number of iterations.