
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the Length of a String in Python
To find how many characters are present in a string (i.e. length of a string), Python provides the built-in function named len(). The length includes all characters in the string, including spaces, punctuation, and special characters.
Using len() Function
The len() function is the most direct way to find out how many characters are in a string. It returns the total number of characters, including spaces and special symbols.
Example
In the following example, we are calculating the length of a string using the len() function -
text = "Python Programming" length = len(text) print("Length of the string is:", length)
Following is the output obtained -
Length of the string is: 18
Using a for Loop
We can also calculate the length of a string manually using a for loop. To do so, we just need to iterate through each character in the string and increase the count value by 1 for each ieteration.
Example
In the following example, we count each character to get the length of the string -
text = "Hello World" count = 0 for char in text: count += 1 print("Length of the string is:", count)
We get the output as shown below -
Length of the string is: 11
Using While Loop
You can also use a while loop to count characters by checking each index one by one until you reach the end of the string.
Example
In this example, we use a while loop to calculate the string length by checking index positions -
text = "OpenAI" count = 0 while count < len(text): count += 1 print("Length of the string is:", count)
The output obtained is as shown below -
Length of the string is: 6
Using List Comprehension
Another way to count the characters in a string is by creating a list using comprehension and then using the sum() function to total the elements.
Example
In this example, we create a list of 1s for each character and sum them to get the length -
text = "Length Test" length = sum([1 for char in text]) print("Length of the string is:", length)
The result produced is as follows -
Length of the string is: 11
Using the slice Operator
We can also calculate the length of a string using the slice operator. We can use the slice operator to traverse through the string, and at each position where a character occurs, we will increment the count by a value. The final value of the count will be the length of the string.
Example
Following is the example -
s1 = "Tutorialspoint" i = 0 while s1[i:]: i += 1 print("The length of the string",s1,"is",i)
The output of the above program is -
The length of the string Tutorialspoint is 14