Open In App

How to find length of a string in Python

Last Updated : 17 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to find length/size of a string in Python.

To find the length of a string, you can use built-in len() method in Python. This function returns the number of characters in the string, including spaces and special characters.

Python
s = "GeeksforGeeks"

# Get the length of given string
length = len(s)

print("Length of the string is:", length)
# Output: Length of the string is: 13

Given string ""GeeksforGeeks" contains 13 characters. Hence, len() method has returned output as 13.

Using len() method is simple and efficient way to find length of Python string. Let's see some alternative methods as well.


Using For loop [less efficient than len() method]

For loop will iterate each character in string, and increment counter by 1 for each character. Note that iterating over each character works slower than len() method.

Python
s = "GeeksforGeeks"

count = 0

# for loop will iterate over each char. in string
for char in s:
  
    # increment counter by 1 for each char count
    count += 1
print("The length of the string is:", count)

You might need to use For Loop for modified length calculation. For example, when you want to skip special character or white-space while calculating the length.


Note:

There can be more methods to find length of string like Using while loop or length = ''.join(my_string).count('') - 1. But they are not efficient to calculating length. Hence, using built-in len() method is recommended to find length of Python string.






Next Article

Similar Reads