Write a Program to find Python String Length. It is one of the frequently asked questions. The python programming language provides a building-in standard function called len. It can help you to find the length of a string in Python or any other object type.
Python String Length Example
In this string length program, we declared an empty string. Next, we find the string length using the len function. Next, we are finding the length of the tutorial gateway and python programming. Remember, Python len function counts empty space as 1. It means the length of he ll is 5.
# Python String Length Example str1 = '' print("\n Original String str1 = ", str1) print("Length of a String str1 = ", len(str1)) str2 = 'Tutorial Gateway' print("\n Original String str2 = ", str2) print("Length of a String str2 = ", len(str2)) str3 = 'Python Programming' print("\n Original String str3 = ", str3) print("Length of a String str3 = ", len(str3))
OUTPUT
String Length Example 2
This program is the same as the first string length example. However, this time, we are allowing the users to enter their own string. Next, we are finding the length of a user given string
TIP: Please refer String article to understand everything about Strings in Python. And also refer the len function.
# String Length Example str1 = input("Please enter the string you want : ") print("\n Original String str1 = ", str1) print("The length of a Given string = ", len(str1))
OUTPUT
Let me try with different string
Python String Length Example 3
In all the above-specified examples, we used the built-in function len. However, you can also find string length without using any built-in function. In real-time, you may not use this. But, in interviews, this can test your coding skills.
In this Python string length program, we are using For Loop to iterate each character in a user given string. Inside the Loop, we increment the length to count the characters in a string. Next, outside the loop, we are printing the final length as an output.
# Python String Length Example str1 = input("Please enter the string you want : ") length = 0 print("\n Original String str1 = ", str1) for i in str1: length = length + 1 print("The length of a Given string = ", length)
OUTPUT
String Length Example 4
In this python string length example, we are using Functions to separate the logic to find the length of a string. Next, we are calling that function to find the length in a user-entered string.
# Python String Length Example def stringLength(string): length = 0 for i in string: length = length + 1 return length str1 = input("Please enter the string you want : ") print("\n Original String str1 = ", str1) strlength = stringLength(str1) print("The length of a Given string = ", strlength)
OUTPUT
Let me re-run and enter a new word. It can help you understand the String Length function in more detail.