Python | Split strings in list with same prefix in all elements
Last Updated : 09 May, 2023
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
test_list = [ 'Rs.25' , 'Rs.100' , 'Rs.143' , 'Rs.12' , 'Rs.4010' ] print ("The original list : " + str (test_list)) res = [sub[ 3 :] for sub in test_list] 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
test_list = [ 'Rs.25' , 'Rs.100' , 'Rs.143' , 'Rs.12' , 'Rs.4010' ] print ("The original list : " + str (test_list)) res = list ( map ( lambda sub: sub[ 3 :], test_list)) 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 test_list = [ 'Rs.25' , 'Rs.100' , 'Rs.143' , 'Rs.12' , 'Rs.4010' ] print ( "The original list:" , test_list) pattern = re. compile (r "Rs\." ) res = [pattern.sub("", elem) for elem in test_list] 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']
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
test_list = [ 'Rs.25' , 'Rs.100' , 'Rs.143' , 'Rs.12' , 'Rs.4010' ] print ( "The original list:" , test_list) res = [elem.removeprefix( "Rs." ) for elem in test_list] 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.
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