Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Python | Ways to split a string in different ways
Next article icon

Python | Ways to split a string in different ways

Last Updated : 26 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples:

Input : Paras_Jain_Moengage_best 

Output : ['Paras', 'Paras_Jain', 'Paras_Jain_Moengage', 'Paras_Jain_Moengage_best'] 

Input : chunky_2808_GFG_Codechef 

Output : ['chunky', 'chunky_2808', 'chunky_2808_GFG', 'chunky_2808_GFG_Codechef']

Below are some ways to do the task.

Method #1: Using Iteration 

Python3
# Python code to split string in substring manner  # Input initialisation Input = "Geeks_for_geeks_is_best"  # Split initialise split_string = Input.split('_')  # Output list initialise Output = []  # Iteration for a in range(len(split_string)):     temp = split_string[:a + 1]     temp = "_".join(temp)     Output.append(temp)  # print output print(Output) 
Output:['Geeks', 'Geeks_for', 'Geeks_for_geeks', 'Geeks_for_geeks_is', 'Geeks_for_geeks_is_best']

Time Complexity: O(n), where n is the length of the string.

Space Complexity: O(n), where n is the length of the string.

Method 2: Using Itertools 

Python3
# Python code to split string in substring manner  # Importing  from itertools import accumulate  # Input initialisation Input = "Geeks_for_geeks_is_best"  # Using accumulate Output = [*accumulate(Input.split('_'), lambda temp1, temp2 :                                    '_'.join([temp1, temp2])), ]  # Printing output print(Output) 
Output:['Geeks', 'Geeks_for', 'Geeks_for_geeks', 'Geeks_for_geeks_is', 'Geeks_for_geeks_is_best']

Time complexity: O(n), where n is the length of the input string.

Auxiliary space: O(n), as we are creating a list to store the output of the accumulate function.

Method#3 : Using re module and string slicing

Python3
# Python code to split string in substring manner # Importing  import re  # Input initialisation Input = "Geeks_for_geeks_is_best"  # Using re module with string slicing to generate substring  ans = [] for i in re.finditer("(_)", Input):     temp = Input[:i.span()[0]]     ans.append(temp)      # inserting last substring  ans.append(Input)  # Printing output print(ans) 

Output:

['Geeks', 'Geeks_for', 'Geeks_for_geeks', 'Geeks_for_geeks_is', 'Geeks_for_geeks_is_best']

Time complexity: O(n), where n is the length of the input string.

Auxiliary space: O(m), where m is the number of substrings generated. 


Next Article
Python | Ways to split a string in different ways

E

everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

    Ways to split strings using newline delimiter - Python
    The goal is to break down the string wherever a newline character (\n, \r, or \r\n) appears, making it easier to process each line individually. For example, in the string "line1\nline2\rline3\r\nline4", different newline characters are used and we aim to efficiently split this string into separate
    2 min read
    Ways to split strings on Uppercase characters - Python
    Splitting strings on uppercase characters means dividing a string into parts whenever an uppercase letter is encountered.For example, given a string like "CamelCaseString", we may want to split it into ["Camel", "Case", "String"]. Let's discuss different ways to achieve this.Using Regular Expression
    3 min read
    Split and join a string in Python
    The goal here is to split a string into smaller parts based on a delimiter and then join those parts back together with a different delimiter. For example, given the string "Hello, how are you?", you might want to split it by spaces to get a list of individual words and then join them back together
    3 min read
    Split a String by a Delimiter in Python
    In Python Programming, the split() method is used to split a string into a list of substrings which is based on the specified delimiter. This method takes the delimiter as an argument and returns the list of substrings. Along with this method, we can use various approaches wot split a string by the
    2 min read
    Python - Double Split String to Matrix
    Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix. Examples: Input : test_str = 'Gfg,best*for,all*geeks,and,CS', row_splt = "*", ele_splt = "," Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS
    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