Write a Program to find the Python String Length. The Python programming language provides a building-in standard function called len to find the length of a string or any other object type.
In this program, we declared an empty string. Next, we find the length of a string in Python using the len function. Next, we find the total characters in the tutorial gateway and learn programming.
Remember, this len function counts empty space as 1. It means the total number of characters in ‘he ll’ is 5.
str1 = '' print("\nstr1 = ", str1) print(len(str1)) str2 = 'Tutorial Gateway' print("\nstr2 = ", str2) print(len(str2)) str3 = 'Learn Programming' print("\nstr3 = ", str3) print(len(str3))
str1 = 0 Tutorial Gateway 16 str3 = Learn Programming 17
This Python string length function program is the same as the first example. However, we allow the users to enter their own words and then find the character count of a user given one.
str1 = input("Please enter the sentence you want : ") print("\n Original str1 = ", str1) print("The length of a Given sentence = ", len(str1))
Please enter the sentence you want : Py Programming Language Original str1 = Py Programming Language The length of a Given sentence = 23
Let me try with different sentences.
Python String Length using for loop
In all the above-specified examples, we used the built-in function len. However, you can also find the length without using any built-in function. Interviews can test your coding skills.
In this program, we are using For Loop to iterate each character in a user-given sentence. Inside the Loop, we increment the val to count the characters. Next, outside the loop, we are printing the final output.
Please refer to Strings, For Loop, and len articles in Python.
str1 = input("Please enter the text you want : ") val = 0 print("\n str1 = ", str1) for i in str1: val = val + 1 print("Total = ", val)
Please enter the text you want : Tutorial Gateway str1 = Tutorial Gateway Total = 16
In this example, we are using Functions to separate the logic to find the length. Next, we are calling that function to find the characters in the user-entered sentence.
def stringLength(string): length = 0 for i in string: length = length + 1 return length str1 = input("Please enter the text you want : ") print("\n str1 = ", str1) strlength = stringLength(str1) print("Characters = ", strlength)
Please enter the text you want : hello str1 = hello Characters = 5
Let me re-run the len program and enter a new word. It can help you understand it in more detail.
Please enter the text you want : Hello Guys str1 = Hello Guys Characters = 10