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 | Append suffix/prefix to strings in list
Next article icon

Python | Split strings in list with same prefix in all elements

Last Updated : 09 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using list comprehension + list slicing This task can be performed using list comprehension and list slicing. List slicing can be used to remove the unwanted letters and list comprehension can be used to extend the logic to the entire string. 

Python3




# Python3 code to demonstrate
# Split strings in list
# Using list comprehension + list slicing
 
# initializing list
test_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + list slicing
# Split strings in list
res = [sub[3:] for sub in test_list]
 
# print result
print("The list after string slicing : " + str(res))
 
 
Output : 
The original list : ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] The list after string slicing : ['25', '100', '143', '12', '4010']

Time complexity: O(n), where n is the length of the test_list. The list comprehension + list slicing takes O(n) time
Auxiliary Space: O(n), where n is the number of elements in the list test_list

  Method #2 : Using map() + slicing + lambda This particular task can be performed using map function as well. The task of performing the same for each string is handled by lambda function and map function. 

Python3




# Python3 code to demonstrate
# Split strings in list
# Using map() + slicing + lambda
 
# initializing list
test_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']
 
# printing original list
print("The original list : " + str(test_list))
 
# using map() + slicing + lambda
# Split strings in list
res = list(map(lambda sub: sub[3:], test_list))
 
# print result
print("The list after string slicing : " + str(res))
 
 
Output : 
The original list : ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] The list after string slicing : ['25', '100', '143', '12', '4010']

Method #3 : Using re

Using regular expressions is another approach for splitting strings in a list with the same prefix in all elements. Regular expressions, or regex for short, are a way to specify patterns in strings. They can be used to search, edit, or manipulate text.

To use regular expressions for this task, you can use the re module, which provides functions and classes for working with regular expressions in Python.

Here is an example of how you can use regular expressions to split strings in a list with the same prefix in all elements:

Python3




import re
 
# initializing list
test_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']
 
# printing original list
print("The original list:", test_list)
 
# using regular expressions
pattern = re.compile(r"Rs\.")  # compile the regex pattern
res = [pattern.sub("", elem) for elem in test_list]  # use the sub() method to remove the prefix
 
# print result
print("The list after string slicing:", res)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list: ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] The list after string slicing: ['25', '100', '143', '12', '4010']

The time and space complexity of the regular expression approach for splitting strings in a list with the same prefix in all elements will depend on the specific implementation and the size of the input.

In general, the time complexity of regular expression matching can be O(n) or O(n * m) in the worst case, where “n” is the size of the input string and “m” is the size of the regex pattern. This is because the regex engine may need to try every possible combination of the pattern and the input to find a match. However, in practice, most regex patterns and inputs will have a much lower time complexity, and the actual time taken to match a regex pattern can depend on various factors such as the structure of the pattern, the type and number of characters in the input, and the performance of the regex engine.

The space complexity of the regular expression approach will be O(n)

Method #4: Using string method removeprefix()

Python 3.9 introduced a new method called removeprefix() to remove a prefix from a string. This method returns a copy of the string with the prefix removed. We can use this method to remove the same prefix from all the strings in a list.

Note: This method only works in Python 3.9 or above.  It wont work in GFG compiler

Python3




#Python3 code to demonstrate
#Split strings in list
#Using string method removeprefix()
#initializing list
test_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']
 
#printing original list
print("The original list:", test_list)
 
#using removeprefix() method
res = [elem.removeprefix("Rs.") for elem in test_list]
 
#print result
print("The list after string slicing:", res)
 
 

Output:
The original list: [‘Rs.25’, ‘Rs.100’, ‘Rs.143’, ‘Rs.12’, ‘Rs.4010’]
The list after string slicing: [’25’, ‘100’, ‘143’, ’12’, ‘4010’]

Time complexity: O(n), where n is the length of the test_list. The list comprehension + removeprefix() method takes O(n) time.
Auxiliary Space: O(n), where n is the number of elements in the list test_list. We are creating a new list to store the modified strings.



Next Article
Python | Append suffix/prefix to strings in list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Check if string starts with any element in list
    We need to check if a given string starts with any element from a list of substrings. Let's discuss different methods to solve this problem. Using startswith() with tuplestartswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the mos
    3 min read
  • Python - Remove similar index elements in Strings
    Given two strings, removed all elements from both, which are the same at similar index. Input : test_str1 = 'geels', test_str2 = 'beaks' Output : gel, bak Explanation : e and s are removed as occur in same indices. Input : test_str1 = 'geeks', test_str2 = 'geeks' Output : '', '' Explanation : Same s
    6 min read
  • Split String into List of characters in Python
    We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
    2 min read
  • Python | Append suffix/prefix to strings in list
    Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed. Method #1: Using + o
    5 min read
  • Find the List elements starting with specific letter - Python
    The goal is to filter the elements of a list that start with a specific letter, such as 'P'. For example, in the list ['Python', 'Java', 'C++', 'PHP'], we aim to find the elements that begin with the letter 'P', resulting in the filtered list ['Python', 'PHP']. Let's explore different approaches to
    3 min read
  • Swap elements in String list - Python
    Swapping elements in a string list means we need to exchange one element with another throughout the entire string list in Python. This can be done using various methods, such as using replace(), string functions, regular expressions (Regex), etc. For example, consider the original list: ['Gfg', 'is
    3 min read
  • Reverse All Strings in String List in Python
    We are given a list of strings and our task is to reverse each string in the list while keeping the order of the list itself unchanged. For example, if we have a list like this: ['gfg', 'is', 'best'] then the output will be ['gfg', 'si', 'tseb']. Using For LoopWe can use a for loop to iterate over t
    2 min read
  • Prefix frequency in string List - Python
    In this article, we will explore various methods to find prefix frequency in string List. The simplest way to do is by using a loop. Using a LoopOne of the simplest ways to calculate the frequency of a prefix in a list of strings is by iterating through each element and checking if the string starts
    2 min read
  • Python - Ways to determine common prefix in set of strings
    A common prefix is the longest substring that appears at the beginning of all strings in a set. Common prefixes in a set of strings can be determined using methods like os.path.commonprefix() for quick results, itertools.takewhile() combined with zip() for a more flexible approach, or iterative comp
    2 min read
  • Split strings ignoring the space formatting characters - Python
    Splitting strings while ignoring space formatting characters in Python involves breaking a string into components while treating irregular spaces, tabs (\t), and newlines (\n) as standard separators. For example, splitting the string "Hello\tWorld \nPython" should result in ['Hello', 'World', 'Pytho
    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