This post will discuss how to split a string with delimiters in Python.

1. Using re.split() function

A simple solution to split a string by the pattern’s occurrences is using the built-in function re.split(). The pattern can consist of one or more delimiters:

⮚ Split on single delimiter

To split a string with a single delimiter, you can simply pass that delimiter to the re.split() function.

Download  Run Code

⮚ Split on multiple delimiters

To split with multiple delimiters, you can do like:

Download  Run Code

⮚ Split on non-alphanumeric characters

To split the string on non-alphanumeric characters, you can use the special character \W, equivalent to [^a-zA-Z0-9_].

Download  Run Code

 
To split on underscore as well, you can use the following code:

Download  Run Code

2. Using re.findall() function

Another alternative is to use the re.findall() function, which returns all non-overlapping matches of a pattern in a string. The following code example demonstrates its usage by using the special character \w, which matches the alphanumeric characters and the underscore.

Download  Run Code

 
The special character \w is the opposite of \W, i.e., it is equivalent to [a-zA-Z0-9_]. To split on underscore as well, you can use the following code:

Download  Run Code

That’s all about splitting a string with delimiters in Python.