Related Tags

python
length of string
len method
array traversal

How to find the length of a string in Python

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

There are two methods to find the length of a string in Python.

Using the len() method

To calculate the length of a string in Python, you can use the built-in len() method.

It takes a string as a parameter and returns an integer as the length of that string. For example, len(“educative”) will return 9 because there are 9 characters in “educative”.





Using the for loop

If you don’t want to use the len() method, you can calculate the length by iterating the string using a for-loop and incrementing a counter variable in every iteration. The following code shows how this is done:

counter = 0for c in "educative": # traverse the string “educative”    counter+=1 #increment the counterprint (counter) # outputs the length (9) of the string “educative”

Here’s how this method works:

1 of 12

RELATED TAGS

python
length of string
len method
array traversal