Python 3 – String len() Method
In Python, you can manipulate strings through various methods. One of the most commonly used methods is the len() method. It is used to determine the length of a string or any other object that returns a length. The len() method returns the number of characters in a given string.
Syntax
The syntax for len() method is very simple. It only takes one argument, which is the string or object that you want to get the length of.
len(object)
Examples
Here are some examples of how to use the len() method:
string = "Hello World"
length = len(string)
print(length) # output: 11
list = [1, 2, 3, 4, 5]
length = len(list)
print(length) # output: 5
dictionary = {'key1': 1, 'key2': 2, 'key3': 3}
length = len(dictionary)
print(length) # output: 3
In these examples, we passed different objects to the len() method to get its length.
Using Len() in String Manipulation
The len() method can be used to manipulate strings in different ways. For instance, you can use it to get the last character of a string or check if a string is empty.
Here’s how to get the last character of a string:
string = "Hello World"
last_char = string[len(string)-1]
print(last_char) # output: d
In this example, we used the len() method to get the length of the string, then subtracted one from it to get the index of the last character.
Here’s how to check if a string is empty:
string = ""
if len(string) == 0:
print("The string is empty")
In this example, we used the len() method to get the length of the string and compared it to zero.
Conclusion
In conclusion, the len() method is a useful tool when it comes to working with strings in Python. It allows you to get the length of a string or any other object that returns a length. With the help of the len() method, you can manipulate strings in different ways such as getting the last character of a string or checking if a string is empty. Knowing how to use the len() method can help you become more efficient in your Python coding.