Split text at positions matched by a regular expression.
How It Works
re.split(pattern, string, maxsplit=0) divides a string using flexible separators. Capturing groups in the separator pattern are included in the resulting list, which may be unexpected.
Step-by-Step Example
import re
print(re.split(r'[,;]\s*', 'red, blue; green'))
print(re.split(r'(,)', 'one,two'))
Understanding the Example
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
['red', 'blue', 'green']
['one', ',', 'two']
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Use str.split() for fixed simple separators because it is easier to understand.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Adding capturing parentheses without realizing the matched delimiters appear in the output.
- Split a list of tokens separated by commas, semicolons, or spaces.
Key Takeaways
- Split text at positions matched by a regular expression.
- re.split(pattern, string, maxsplit=0) divides a string using flexible separators.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.