The `split()` function in the `re` module is used to split a string into substrings based on a specified pattern and returns a list of substrings. Here are several illustrative examples of using the `split()` function:
1. Splitting a String by Space:
“`python
import re
# Test string
test_string = “Hello World! This is a test string.”
# Split the string by space using split()
result = re.split(r’s+’, test_string)
# Print the result
print(“After splitting by space:”, result)
“`
Output:
“`
After splitting by space: [‘Hello’, ‘World!’, ‘This’, ‘is’, ‘a’, ‘test’, ‘string.’]
“`
2. Splitting a String by Comma:
“`python
import re
# Test string
test_string = “apple,banana,orange,grape”
# Split the string by comma using split()
result = re.split(r’,’, test_string)
# Print the result
print(“After splitting by comma:”, result)
“`
Output:
“`
After splitting by comma: [‘apple’, ‘banana’, ‘orange’, ‘grape’]
“`
3. Splitting a String by Multiple Delimiters:
“`python
import re
# Test string
test_string = “apple,banana;orange.grape”
# Split the string by comma, semicolon, or period using split()
result = re.split(r'[,;.]’, test_string)
# Print the result
print(“After splitting by multiple delimiters:”, result)
“`
Output:
“`
After splitting by multiple delimiters: [‘apple’, ‘banana’, ‘orange’, ‘grape’]
“`
4. Splitting a String by Word Boundaries:
“`python
import re
# Test string
test_string = “This is a test string.”
# Split the string by word boundaries using split()
result = re.split(r’b’, test_string)
# Print the result
print(“After splitting by word boundaries:”, result)
“`
Output:
“`
After splitting by word boundaries: [”, ‘This’, ‘ ‘, ‘is’, ‘ ‘, ‘a’, ‘ ‘, ‘test’, ‘ ‘, ‘string’, ‘.’]
“`
These examples demonstrate how the `split()` function can be used to split a string into substrings based on a specified pattern, providing flexibility in handling various text processing tasks.