Finding the Length of a String in Python

To find the length of a string in Python, you can use the built-in len() method. The len() method returns the length of the passed object (String, List, Tuple, Dictionary, etc.). The len() method uses the stored value of the length of the string and does not calculate it every time, so it is very fast. In this Python String Length example, we calculate the length of the provided string using the len() method. Click Execute to run the Python String Length example online and see the result.
Finding the Length of a String in Python Execute
string = 'Python'

print("length =", len(string))
Updated: Viewed: 1758 times

Python len() method syntax

You can use len() method to get the length of a given string, array, list, tuple, dictionary, etc. It is allowed to have a null-character string written the same '' " as an empty string. The length of the empty string is 0.

Python len() Syntax

  • object: specified sequence or collection

How to find the length of a string using a for loop in Python?

Using a for loop, we can iterate over each character in the string one by one. Initialize one counter variable with an initial value of zero. Keep incrementing this counter variable by one for each character as you iterate. At the end of the loop, the counter will record the length of the string.

Python find the length of a string Example
string = 'I like to program in Python'

counter = 0
for i in string:
    counter += 1
print("length =", counter)

# length = 27

See also