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

Python Code Editor:

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

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.