Skip to main content

How to find the length of a string in Python

How to find the length of a string in Python.

Here is a step-by-step tutorial on how to find the length of a string in Python:

Step 1: Understand the concept The length of a string refers to the number of characters it contains. Python provides a built-in function called len() to find the length of a string.

Step 2: Declare a string Start by declaring a string variable that you want to find the length of. For example, let's declare a string variable named my_string with the value "Hello, World!".

Step 3: Use the len() function To find the length of a string, simply pass the string variable as an argument to the len() function. In this case, we'll pass my_string as the argument and assign the result to a new variable called string_length.

my_string = "Hello, World!"
string_length = len(my_string)

Step 4: Print the length To see the length of the string, we can use the print() function to display the value of string_length.

print("The length of the string is:", string_length)

Step 5: Run the code Save the file with a .py extension (e.g., string_length.py) and run the code. The output will be:

The length of the string is: 13

Alternative method: Instead of assigning the length to a variable, you can directly print the length using the print() function.

my_string = "Hello, World!"
print("The length of the string is:", len(my_string))

This will produce the same output as before.

That's it! You have successfully found the length of a string in Python using the len() function.