How to Split String by Multiple Delimiters in Python
To split a string by multiple delimiters in Python, use the
re.split() function from the re module with a pattern that includes all delimiters separated by the pipe | symbol. This lets you split the string wherever any of the delimiters appear.Syntax
The syntax to split a string by multiple delimiters uses the re.split() function:
re.split(pattern, string): Splitsstringby the regexpattern.pattern: A regular expression where delimiters are separated by|(meaning OR).
python
import re result = re.split(r'[;,.]', 'apple;banana,orange.mango')
Output
['apple', 'banana', 'orange', 'mango']
Example
This example shows how to split a string by multiple delimiters like comma, semicolon, and space.
python
import re text = 'apple,banana;orange mango' delimiters = r'[;, ]+' result = re.split(delimiters, text) print(result)
Output
['apple', 'banana', 'orange', 'mango']
Common Pitfalls
One common mistake is trying to use str.split() multiple times or passing a list of delimiters directly, which does not work. Another is forgetting to escape special characters in delimiters or not using raw strings for regex patterns.
Always use re.split() with a proper regex pattern and raw string notation (prefix r) to avoid errors.
python
import re # Wrong: str.split() does not accept multiple delimiters text = 'apple,banana;orange' # result = text.split([',', ';']) # This raises TypeError # Right way: delimiters = r'[;,]' result = re.split(delimiters, text) print(result)
Output
['apple', 'banana', 'orange']
Quick Reference
Tips for splitting strings by multiple delimiters:
- Use
re.split()with a regex pattern combining delimiters using|or character classes[]. - Use raw strings (prefix
r) for regex patterns to avoid escape issues. - Include
+after delimiters to split on one or more consecutive delimiters. - Remember
str.split()only works with a single delimiter string.
Key Takeaways
Use the re.split() function with a regex pattern to split by multiple delimiters.
Combine delimiters in the pattern using | or character classes [] inside a raw string.
str.split() cannot split by multiple delimiters at once.
Use + in regex to handle consecutive delimiters as one split point.
Always test your regex pattern to ensure correct splitting.