Python | Remove trailing/leading special characters from strings list
Last Updated :
16 May, 2023
Sometimes, while working with String lists, we can have a problem in which we need to perform the deletion of extra characters that can be termed as unwanted and occur at end of each string. Let’s discuss a way in which this task can be performed.
Method 1: Using map() + str.strip()
A combination of the above two functionalities can help us achieve this particular task. In this, we employ strip(), which has the ability to remove the trailing and leading special unwanted characters from string list. The map(), is used to extend the logic to each element in list.
Python3
test_list = [ '\rgfg\t\n' , 'is\n' , '\t\tbest\r' ]
print ( "The original list : " + str (test_list))
res = list ( map ( str .strip, test_list))
print ( "List after removal of special characters : " + str (res))
|
Output
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. map() + str.strip() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method 2: Using split() and join() methods
Python3
test_list = [ '\rgfg\t\n' , 'is\n' , '\t\tbest\r' ]
print ( "The original list : " + str (test_list))
res = []
for i in test_list:
res.append("".join(i.split()))
print ( "List after removal of special characters : " + str (res))
|
Output
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']
Method 3: Using regex
Explanation: Using the re module, we can use a regular expression to match and remove any trailing or leading special characters from the list of strings.
Python3
import re
test_list = [ '\rgfg\t\n' , 'is\n' , '\t\tbest\r' ]
print ( "The original list : " + str (test_list))
res = [re.sub(r '^[^A-Za-z0-9]+|[^A-Za-z0-9]+$' , '', i) for i in test_list]
print ( "List after removal of special characters : " + str (res))
|
Output
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']
Time complexity: O(n), where n is the length of the list
Auxiliary Space: O(n), where n is the length of the list
Method 3: Using list comprehension:
Python3
test_list = [ '\rgfg\t\n' , 'is\n' , '\t\tbest\r' ]
print ( "The original list : " + str (test_list))
res = [x.strip() for x in test_list]
print ( "List after removal of special characters : " + str (res))
|
Output
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']
Time Complexity: O(N)
Auxiliary Space: O(N)
Method#4: Using Recursive method.
Algorithm:
- If the input list is empty, return an empty list.
- Strip leading and trailing special characters from the first element of the list.
- Recursively, call strip_list_recursive function on the rest of the list (i.e., all elements except the first).
- Combine the stripped first element and the recursive result (i.e., stripped rest of the list) into a new list.
- Return the new list.
Python3
def strip_list_recursive(lst):
if not lst:
return lst
else :
first = lst[ 0 ].strip()
rest = strip_list_recursive(lst[ 1 :])
return [first] + rest
test_list = [ '\rgfg\t\n' , 'is\n' , '\t\tbest\r' ]
print ( "The original list : " + str (test_list))
res = strip_list_recursive(test_list)
print ( "List after removal of special characters : " + str (res))
|
Output
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']
Time complexity: O(n * m), where n is the length of the input list and m is the maximum length of any element in the list. This is because we need to call the strip() method on each element, which takes O(m) time, and we need to do this for each element in the list.
Auxiliary Space: O(n * m), where n is the length of the input list and m is the maximum length of any element in the list. This is because we are creating a new list of stripped elements, which takes up O(n * m) space in the worst case (when all elements in the list have maximum length m). Additionally, the recursive call stack can take up to O(n) space, since we need to make n recursive calls in the worst case (when the input list is not empty).
Method#5: Using a lambda function with the replace() method
In this method, we use a lambda function that takes each string in the test_list and uses the replace() method with the map() function to remove the special characters. The resulting list is then stored in res and printed using the print() function.
Python3
test_list = [ '\rgfg\t\n' , 'is\n' , '\t\tbest\r' ]
print ( "The original list : " + str (test_list))
res = list ( map ( lambda x: x.replace( '\n' , ' ').replace(' \t ', ' ').replace(' \r ', ' '), test_list))
print ( "List after removal of special characters : " + str (res))
|
Output
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']
Time complexity: O(n), where n is the length of the original list.
Auxiliary Space: O(n), where n is the length of the original list, because we are creating a new list with the same number of elements as the original list.
Similar Reads
Remove Special Characters from String in Python
When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Python | Remove given character from Strings list
Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem. Method #1 : Using replace() + enumerate() + loop This is
8 min read
Python - Remove front K characters from each string in String List
Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a
6 min read
Python | Remove Kth character from strings list
Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
7 min read
Python - Remove leading 0 from Strings List
Sometimes, while working with Python, we can have a problem in which we have data which we need to perform processing and then pass the data forward. One way to process is to remove a stray 0 that may get attached to a string while data transfer. Let's discuss certain ways in which this task can be
5 min read
Python - Remove Rear K characters from String List
Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
5 min read
Removing newline character from string in Python
When working with text data, newline characters (\n) are often encountered especially when reading from files or handling multi-line strings. These characters can interfere with data processing and formatting. In this article, we will explore different methods to remove newline characters from strin
2 min read
Remove Multiple Characters from a String in Python
Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Letâs explore the different ways to achieve this in det
3 min read
Python | Ways to remove n characters from start of given string
Given a string and a number 'n', the task is to remove a string of length 'n' from the start of the string. Let's a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising st
3 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
2 min read