Python Program to find a String Length

Write a Python Program to find a String Length using the built-in len function with practical examples. This programming language has a built-in function, len(), and we can use this function to find the length of the string. Apart from this, you can also use the for loop or while loop to get the result.

The Python length of the string is simply the total number of characters, which includes letters, symbols, numbers, and white spaces it contains.

Python Program to find a String Length using len()

Using a built-in common function such as len() is one of the most effective and straightforward ways to find the length. This function accepts any object that includes a list, tuple, set, or string. The program finds the string length using the len function.

This example starts with defining a string (str1), which contains a text that is “Tutorial Gateway”. Next, within the print statement, we use the len() function to find the length of the defined string (including space). However, you can define another variable to assign the length if you want.

Please refer to the String article to understand everything about them in Python.

str1 = "Tutorial Gateway"

print("Total = ", len(str1))
Total =  16

This Python program is the same as the first example. However, this time, we are allowing the user to enter their own string.

str1 = input("Please enter your own String : ")

print("Total Length of a Given String = ", len(str1))
Python Program to find a String Length using len function

Python Program to find a String Length using for loop

If you don’t want to use any built-in function, you can try either for loop or while loop. This program uses the for loop to iterate each character and increment the counter variable until it reaches the end of the string. Don’t forget to initialize the count variable to zero.

def strChars(text):
    count = 0

    for ch in text:
        count += 1
    return count

txt = input("Please enter Text = ")
print(strChars(txt))
Python Program to find a String Length using for loop