Python, a versatile and powerful programming language, offers built-in functions that come in handy for a wide range of tasks.
One such function is len(), used primarily to determine the string length, or in other words, count the number of characters (including whitespace and special characters) in a string, but using it for a string is the most popular case. In this tutorial, we’ll examine how to utilize Python’s len() function to find a string’s length.
Step 1: Understanding len()
The len() function in Python accepts an iterable (like a string, list, array, etc.) as an argument and returns the number of elements in that iterable, which, for strings, corresponds to the number of characters. For example, if we have a string “Hello World!”, the length of this string calculated by Python’s len() function would be 12 characters.
Step 2: Using len() with a String
To use the len() function, you need to put the name of the string you want to find the length of, inside the round bracket following len(). Here is an example:
1 2 3 |
string_example = "Hello, World!" length = len(string_example) print(length) |
In the above example, the len() function is counting the number of characters in the string “Hello, World!”, including the special character comma and the white spaces.
Step 3: Displaying the Length of the String
The return value of the len() function in the previous example was stored in a variable called ‘length’, which was then printed out. As a result, when this program runs, the output would be:
13
The number 13 which is the length of the string (number of characters) in “Hello, World!” is printed out as the output.
Step 4: Using len() Function Directly in Print Statement
If you want to do it more directly, you could use the len() function directly in a print statement, as follows:
1 |
print(len("Hello, World!")) |
Once again, the output would be the same:
13
That’s how easy it is to find the string length in Python!
The Full Code
For easy reference, here are the complete program codes used in the examples:
1 2 3 4 5 6 7 |
# Code1 string_example = "Hello, World!" length = len(string_example) print(length) # Code2 print(len("Hello, World!")) |
Conclusion
Knowing how to compute the string length can be incredibly useful in numerous Python programming scenarios – from simple data validation checks to complex data manipulation. By learning to use Python’s built-in len() function, you have added yet another tool to your Python programming arsenal. Happy coding!