Determine the Length of a Given String
In this section, we will define a string and check its length using different methods.
Example 1: Using the Built-in len()
Method
str = "runoob" print(len(str))
Output:
6
In this example, the built-in len()
method is used to directly calculate the length of the string.
Example 2: Using a Loop to Calculate Length
def findLen(str): counter = 0 while str[counter:]: counter += 1 return counter
Code Example:
str = "runoob" print(findLen(str))
Output:
6
In this example, we manually count the number of characters in the string using a loop. The loop increments the counter until it reaches the end of the string, giving us the length.