Python String Length

Write a Program to find Python String Length. The python programming language provides a building-in standard function called len. It can help you 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 are finding 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 program is the same as the first Python string length 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 : Python Programming Language

 Original str1 =  Python Programming Language
The length of a Given sentence =  27

Let me try with different sentences

Python String Length 3

Python String Length Example

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. 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 sentence. Inside the Loop, we increment the val to count the characters. Next, outside the loop, we are printing the final output.

Please refer 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 Original str1 = ", str1)

strlength = stringLength(str1)

print("Characters  = ", strlength)
Please enter the text you want : hello

 Original 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 : Python Tutorial

 str1 =  Python Tutorial
Characters  =  15