In addition to the basic slicing techniques covered in the previous section, Python provides various methods and functions to extract substrings from a larger string. These methods offer more specialized and powerful ways to manipulate and retrieve specific parts of a string.
Using the find()
and index()
Methods
The find()
and index()
methods are used to locate the position of a substring within a string. The main difference between them is that find()
returns -1
if the substring is not found, while index()
raises a ValueError
exception.
my_string = "LabEx is awesome!"
print(my_string.find("Ex")) ## Output: 3
print(my_string.index("is")) ## Output: 6
print(my_string.find("xyz")) ## Output: -1
Splitting Strings with split()
The split()
method is used to split a string into a list of substrings based on a specified separator. By default, it uses whitespace as the separator.
my_string = "LabEx,is,awesome!"
parts = my_string.split(",")
print(parts) ## Output: ['LabEx', 'is', 'awesome!']
Extracting Substrings with startswith()
and endswith()
The startswith()
and endswith()
methods check if a string starts or ends with a specified substring, respectively. They return a boolean value.
my_string = "LabEx is awesome!"
print(my_string.startswith("Lab")) ## Output: True
print(my_string.endswith("!")) ## Output: True
Using Regular Expressions
For more advanced substring extraction, you can leverage the power of regular expressions (regex) using the re
module in Python. Regular expressions provide a flexible and powerful way to search, match, and extract patterns from strings.
import re
my_string = "LabEx is awesome! Contact us at info@labex.io"
email = re.search(r'\b\w+@\w+\.\w+\b', my_string).group()
print(email) ## Output: info@labex.io
By combining these techniques, you can efficiently extract and manipulate substrings within Python strings to meet your specific requirements.