How to Find the Length of a String in Python
In this tutorial, you'll learn how to find the length of a given string using the built-in len() function in Python. Also, this tutorial provides sample programs that show you how to count the number of characters in the string using the FOR loop and WHILE loop statements.
Using the Python len() Built-in Function
To get the length of a given string using the len() function, you use the following syntax:
len(string)
Where the string argument is the string that you want to get its length.
Examples
The following program returns the length of the string:
#get the length of a string using the len() functionstring = "How do I get the number of characters in the string?"string_length = len(string)print("The length of the string is", string_length)
Result:
The length of the string is 52
Using the FOR Loop Statement
You also can get the length of a given string without using the built-in function.
In this section, You'll learn to write programs to count the number of characters in the string using the FOR loop and WHILE loop statements.
The following program loops through the string and counts the number of characters using the FOR loop statement:
#count the number of characters using the FOR loop statementstring = "I want to learn to code in Python programming language."number = 0#loop through the stringfor i in string:number += 1print("The number of characters is ", number)
Result:
The number of characters is 55
Count Characters Using the WHILE Loop Statement
The following example counts the number of characters using the WHILE loop statement:
#count the number of characters using the WHILE loop statementstring = "How can I count the number of characters using the WHILE loop?"count = 0while(string[count:]):count += 1print("The number of characters is ", count)
Result:
The number of characters is 62
In this tutorial, you've learned how to get the length of a given string using the len() function in Python. Also, you've learned to write a sample program to count the number of characters and return the length of the string without using the built-in function.