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:
Python | Sort given list of strings by part of string
Next article icon

Python program to split a string by the given list of strings

Last Updated : 08 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of strings. The task is to split the string by the given list of strings. 

Input : test_str = ‘geekforgeeksbestforgeeks’, sub_list = [“best”] 
Output : [‘geekforgeeks’, ‘best’, ‘forgeeks’] 
Explanation : “best” is extracted as different list element.

Input : test_str = ‘geekforgeeksbestforgeeksCS’, sub_list = [“best”, “CS”] 
Output : [‘geekforgeeks’, ‘best’, ‘forgeeks’, “CS”] 
Explanation : “best” and “CS” are extracted as different list element. 
 

Method : Using re.split() + | operator

In this, we perform the task of split using regex split() with | operator to check for all the words that need to be put separately.

Python3




# Python3 code to demonstrate working of
# Separate specific Strings
# Using re.split() + | operator
import re
 
# initializing string
test_str = 'geekforgeeksisbestforgeeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing list words
sub_list = ["best"]
 
# regex to for splits()
# | operator to include all strings
temp = re.split(rf"({'|'.join(sub_list)})", test_str)
res = [ele for ele in temp if ele]
 
# printing result
print("The segmented String : " + str(res))
 
 
Output
The original string is : geekforgeeksisbestforgeeks The segmented String : ['geekforgeeksis', 'best', 'forgeeks']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method : Using replace(),split() methods

Approach

  1. Initiate a for loop to traverse list of strings
  2. Replace the string in original string by appending “*” front and back
  3. Finally split the string with * as parameter
  4. This will return a list, display the list

Python3




# Python3 code to demonstrate working of
# Separate specific Strings
 
# initializing string
test_str = 'geekforgeeksisbestforgeeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing list words
sub_list = ["best"]
for i in sub_list:
    test_str=test_str.replace(i,"*"+i+"*")
res=test_str.split("*")
 
# printing result
print("The segmented String : " + str(res))
 
 
Output
The original string is : geekforgeeksisbestforgeeks The segmented String : ['geekforgeeksis', 'best', 'forgeeks']

Time Complexity : O(N)
Auxiliary Space : O(N)

Method 3 :  Use the re module

 step by step approach :

  1. The program starts by importing the “re” module. This module provides regular expression operations in Python.
  2. The program then initializes a string variable named “test_str” with the value “geekforgeeksisbestforgeeks”.
  3. The program then prints the original string using the “print” statement and concatenating the original string with a string literal.
  4. The program initializes a list variable named “sub_list” with the value [“best”].
  5. The program creates a regular expression pattern by joining the elements of the “sub_list” with a pipe symbol “|”. The pipe symbol is used to separate the substrings in the pattern. The resulting pattern is assigned to the variable “pattern”.
  6. The program then splits the original string “test_str” using the regular expression pattern stored in the variable “pattern”. The resulting segments are stored in the variable “res”.
  7. Finally, the program prints the segmented string using the “print” statement and concatenating the segmented string with a string literal.

Python3




import re
 
# initializing string
test_str = 'geekforgeeksisbestforgeeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing list words
sub_list = ["best"]
 
# add a '|' between the substrings to create the pattern for splitting
pattern = '|'.join(sub_list)
 
# split the string using the pattern
res = re.split(pattern, test_str)
 
# printing result
print("The segmented String : " + str(res))
 
 
Output
The original string is : geekforgeeksisbestforgeeks The segmented String : ['geekforgeeksis', 'forgeeks']

Time complexity: The replace() method has a time complexity of O(n), where n is the length of the string. 

Auxiliary space: The original string is replaced with a new string, which has a space complexity of O(n). The segmented string is stored in a list, which has a space complexity of O(m), where m is the number of substrings. Overall, the space complexity is O(n+m).



Next Article
Python | Sort given list of strings by part of string
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Sort given list of strings by part of string
    We are given with a list of strings, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string. Using sort() with lambda functionThis
    3 min read
  • Sort given list of strings by part the numeric part of string - Python
    We are given a list of strings containing both letters and numbers, and the goal is to sort them based on the numeric part within each string. To do this, we extract the digits, convert them to integers and use them as sorting keys. For example, in ["Gfg34", "is67", "be3st"], the numbers 34, 67, and
    3 min read
  • Python Program to split string into k sized overlapping strings
    Given a string, the task is to write a Python program to extract overlapping consecutive string slices from the original string according to size K.  Example: Input : test_str = 'Geeksforgeeks', K = 4 Output : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks'] Explanati
    4 min read
  • Python | Splitting string list by strings
    Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
    3 min read
  • Splitting String to List of Characters - Python
    We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python. Using list()The simplest way to split a string i
    2 min read
  • Splitting String to List of Characters - Python
    The task of splitting a string into a list of characters in Python involves breaking down a string into its individual components, where each character becomes an element in a list. For example, given the string s = "GeeksforGeeks", the task is to split the string, resulting in a list like this: ['G
    3 min read
  • Python | Split strings and digits from string list
    Sometimes, while working with String list, we can have a problem in which we need to remove the surrounding stray characters or noise from list of digits. This can be in form of Currency prefix, signs of numbers etc. Let's discuss a way in which this task can be performed. Method #1 : Using list com
    5 min read
  • Python program to find String in a List
    Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, we’ll explore several methods to find a string in a list, starting from the most e
    3 min read
  • Python - Find all the strings that are substrings to the given list of strings
    Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation
    5 min read
  • Python Program to Convert a List to String
    In Python, converting a list to a string is a common operation. In this article, we will explore the several methods to convert a list into a string. The most common method to convert a list of strings into a single string is by using join() method. Let's take an example about how to do it. Using th
    3 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