How do I find 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. In this Python String Length example, the len() method takes a string as a parameter, calculates the length of the string, and returns that length as an integer. Alternatively, you can calculate the length of the string by iterating over the string with a for loop and incrementing the counter variable with each iteration. By tracking the number of iterations, you can get the length of the string. In this Python Example, we determine the length of the string by calling the len() method on the specified string and printing the return value. Click Execute to run the Python find string length Example online and see the result.
How do I find the length of a string in Python? Execute
string = 'Python'

print("length =", len(string))
Updated: Viewed: 715 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
len(object)

Where:
  • 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