Working with strings is a common task in any programming language. In Python, a string is a sequence of characters. There are many operations that can be performed with strings which makes Python a powerful language for string manipulation.
One of the common operations that you often perform with strings is determining its length. In this tutorial, you’re going to learn how to get the length of a string in Python.
Step 1: Understanding Python Strings
A string in Python is an ordered collection of characters, used to represent text-based data. Strings are defined either with single quotes ‘ ‘ or double quotes ” “. They are immutable, meaning their values cannot be changed once they have been assigned. For instance:
1 |
my_string = 'Hello, World!' |
The string ‘Hello, World!’ is now stored in the variable ‘my_string’.
Step 2: Using the len() Function
Python provides a built-in function called len() that returns the length of the given string. It counts the number of characters in the string including spaces and punctuation.
Here’s how to use it:
1 2 |
my_string = 'Hello, World!' print(len(my_string)) |
This will output:
13
The length of the string ‘Hello, World!’ is 13 as it contains 13 characters including spaces and punctuation.
Step 3: Handling Unicode Strings
If your string contains Unicode characters, you will still use the len() function to get its length. However, it’s important to note that Python counts each Unicode character as a single character.
For example:
1 2 |
my_string = '你好,世界!' print(len(my_string)) |
This will output:
6
The string ‘你好,世界!’ contains 6 unicode characters, so the len() function correctly returns 6.
Full code:
1 2 3 4 5 |
my_string = 'Hello, World!' print(len(my_string)) my_string = '你好,世界!' print(len(my_string)) |
Conclusion
That’s actually all there is to it! With Python’s len() function, you can easily get the length of any string, regardless of whether it contains standard or Unicode characters. In this short tutorial, you’ve learned a basic but powerful aspect of string manipulation in Python. Happy coding!