Python Regex Split : How to Split String in Python with Regex

Python Regex Split _ How to Split String in Python with Regex

Let’s say you have a string and want to split a string. Then how you can do so? In this tutorial, you will learn how to split a string using the regex module with steps.

Steps to Implement python regex split

In this section, you will know all the steps that you will follow to split a string. Just follow the step for better understanding.

Step 1: Import the required library.

The first step is to import all the necessary libraries that will be used in the implementation part. Let’s import it using the import statement.

import re

Step 2: Create a string

The second step is to create a string where you will use the regex module to split. Use the below line of code to create a string.

sample_string = "Hello, World! Welcome to data science learner"

Step 3: Define a pattern

Now after creating a string, you will define the pattern that will be used to tell the python interpreter from where you have to split the string. In my example, I will split the string after any non-numeric or nom-alphabetical character and space.

Use the blow line of code to define the pattern.

pattern = r"[^\w']+" 

Step 4: Use the python regex split function split()

After defining the regex pattern you will use the re.split() function to split a string. Additionally, You have to just pass two parameters. One is the pattern and the other is your input string.

result = re.split(pattern, sample_string)

Step 5: Output the result

The re.splt() function will return a list of substrings that will split from your input string. Assign it to a variable and use the print() function to display it.

Add the below line of code.


Below is the full code

import re
sample_string = "Hello, World! Welcome to data science learner"
pattern = r"[^\w']+" 
result = re.split(pattern, sample_string)


splitting the string using the pattern
splitting the string using the pattern


Sometimes you want a string to be split in order to get tokens. You can use a regex pattern to split the string using any pattern. The regex module will check the string for any pattern and split the string. The above steps are the answer to your question on how to split a string using the regex module.

I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner