w3resource

Python: Calculate the length of a string


Calculate string length.

Write a Python program to calculate the length of a string.

Python String Exercises: Calculate the length of a string

Sample Solution:

Python Code:

# Define a function named string_length that takes one argument, str1.
def string_length(str1):
    # Initialize a variable called count to 0 to keep track of the string's length.
    count = 0

    # Iterate through each character in the input string str1.
    for char in str1:
        # For each character encountered, increment the count by 1.
        count += 1

    # Return the final count, which represents the length of the input string.
    return count

# Call the string_length function with the argument 'w3resource.com' and print the result.
print(string_length('w3resource.com')) 

Sample Output:

14

Flowchart:

Flowchart: Program to calculate the length of a string

For more Practice: Solve these Related Problems:

  • Write a Python program to calculate the length of a string recursively without using the built-in len() function.
  • Write a Python program to determine the length of a string by converting it to a list and summing 1 for each element.
  • Write a Python program to compute the length of a string using a for-loop that increments a counter for each character.
  • Write a Python program to use list comprehension and the sum() function to calculate the total number of characters in a string.

Go to:


Previous: Python String Exercise Home.
Next: Write a Python program to count the number of characters (character frequency) in a string.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.