w3resource

Python: Calculate the length of a string

Python String: Exercise-1 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/string/python-data-type-string-exercise-1.php