There are two methods to find the length of a string in Python.
To calculate the length of a string in Python, you can use the built-in
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”.
<img src="/api/edpresso/shot/4858395446214656/image/5649050225344512" alt=“Markdown Monster icon”
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 = 0 for c in "educative": # traverse the string “educative” counter+=1 #increment the counter print (counter) # outputs the length (9) of the string “educative”
Here’s how this method works:
View all Courses