Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Use of slice() in Python
Next article icon

re.split() in Python

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The re.split() method in Python is used to split a string by a pattern (using regular expressions). It is part of the re-module, which provides support for working with regular expressions. This method is helpful when we need to split a string into multiple parts based on complex patterns rather than just simple delimiters like spaces or commas.

Let’s understand how to use re.split() with an example.

Python
import re  # Original string s = "geeks,for;geeks gfg"  # Split the string by commas, semicolons, or spaces result = re.split(r"[,\s;]+", s)  print(result) 

Output
['geeks', 'for', 'geeks', 'gfg'] 

Syntax of re.split()

re.split(pattern, string, maxsplit=0, flags=0)

Parameters

  • pattern: The regular expression (pattern) that we want to use to split the string.
  • string: The original string to be split.
  • maxsplit (optional): The maximum number of splits to do. If omitted or set to 0, there is no limit to the number of splits.
  • flags (optional): Flags to modify the behavior of the regular expression, such as re.IGNORECASE for case-insensitive matching.

Return Type

  • The method returns a list of strings, which are the parts of the original string split by the specified pattern.

Limiting the Number of Splits

In some cases, we may not want to split the string into as many parts as possible. Instead, we might want to limit the number of splits, so that the result has fewer elements. This is where the maxsplit argument comes in. It controls how many times the string will be split.

Python
import re  # Original string s = "geeks for geeks gfg"  # Split the string by space, but limit the number of splits to 2 result = re.split(r"\s+", s, maxsplit=2)  print(result) 

Output
['geeks', 'for', 'geeks gfg'] 

Explanation

  • The string is split into a maximum of 3 parts (because maxsplit=2 limits the splits to 2). The output will contain the first 2 splits and the rest will stay in the last part.

Splitting with Capture Groups

One powerful feature of regular expressions is the ability to use capture groups. A capture group is a part of the regular expression pattern enclosed in parentheses. When we use capture groups in re.split(), the matched part of the pattern is included in the result along with the rest of the string.

Python
import re  # Original string s = "geeks123for456geeks"  # Split the string at numbers, keeping the numbers in the result result = re.split(r"(\d+)", s)  print(result) 

Output
['geeks', '123', 'for', '456', 'geeks'] 

Explanation

  • The pattern (\d+) matches one or more digits. The parentheses create a capture group, so the numbers are included in the result along with the other parts of the string.

Next Article
Use of slice() in Python

P

pragya22r4
Improve
Article Tags :
  • Python
  • Python Programs
  • python-regex
  • python
Practice Tags :
  • python
  • python

Similar Reads

  • Python | Custom list split
    Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed. This is quite a useful utility to have knowledge about. Let's discuss certain ways in which this task can be performed. Method
    8 min read
  • How to Split Lists in Python?
    Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
    3 min read
  • Use of slice() in Python
    In Python, slice() is used to access a portion of a sequence such as a list or tuple. It helps improve code readability and maintainability by giving meaningful names to slices instead of using hardcoded indices. For example: slice(1, 5, 2) corresponds to a[1:5:2] and slice(1, 4) corresponds to a[1:
    3 min read
  • Python - Selectively Split in Strings
    Sometimes, while working with Python strings, we may have to perform a split. Not sometimes, normal one, depending on deliminator but something depending upon programming constructs like elements, numbers, words etc and segregate them. Lets discuss a way in which this task can be solved. Method : Us
    3 min read
  • Python - Reversed Split Strings
    In Python, there are times where we need to split a given string into individual words and reverse the order of these words while preserving the order of characters within each word. For example, given the input string "learn python with gfg", the desired output would be "gfg with python learn". Let
    3 min read
  • Python - Split in Nested tuples
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let's discuss certain ways in which this task can be performed. Input : test_
    7 min read
  • Python - String Split including spaces
    String splitting, including spaces refers to breaking a string into parts while keeping spaces as separate elements in the result. Using regular expressions (Most Efficient)re.split() function allows us to split a string based on a custom pattern. We can use it to split the string while capturing th
    3 min read
  • Python - Phrase removal in String
    Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
    2 min read
  • Python | Reverse Interval Slicing String
    Sometimes, while working with strings, we can have a problem in which we need to perform string slicing. In this, we can have a variant in which we need to perform reverse slicing that too interval. This kind of application can come in day-day programming. Let us discuss certain ways in which this t
    4 min read
  • Python - Cumulative List Split
    Sometimes, while working with String lists, we can have a problem in which we need to perform the task of split and return all the split instances of list in cumulative way. This kind of problem can occur in many domains in which data is involved. Lets discuss certain ways in which this task can be
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences