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
Split Elements of a List in Python
Splitting elements of a list in Python means dividing strings inside each list item based on a delimiter. split() Method is the easy and most straightforward method to split each element is by using the split() method. This method divides a string into a list based on a delimiter. Here's how we can
2 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
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
Python | Sort all sublists in given list of strings
Sorting sublists in a list of strings refers to arranging the elements within each sublist in a specific order. There are multiple ways to sort each list in alphabetical order, let's understand each one by one. Using list comprehensionList comprehension with sorted() allows efficient sorting of each
2 min read
Python | Check if string ends with any string in given list
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using filte
6 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
Python | Split list of strings into sublists based on length
Given a list of strings, write a Python program to split the list into sublists based on string length. Examples: Input : ['The', 'art', 'of', 'programming'] Output : [['of'], ['The', 'art'], ['programming']] Input : ['Welcome', 'to', 'geeksforgeeks'] Output : [['to'], ['Welcome'], ['geeksforgeeks']
3 min read