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:
Remove Special Characters from String in Python
Next article icon

Python | Remove trailing/leading special characters from strings list

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

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




# Python3 code to demonstrate working of
# Remove trailing / leading special characters from strings list
# Using map() + str.strip()
 
# initializing list
test_list = ['\rgfg\t\n', 'is\n', '\t\tbest\r']
 
# printing list
print("The original list : " + str(test_list))
 
# Remove trailing / leading special characters from strings list
# Using map() + str.strip()
res = list(map(str.strip, test_list))
 
# Printing result
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




# Python3 code to demonstrate working of
# Remove trailing / leading special characters from strings list
 
# initializing list
test_list = ['\rgfg\t\n', 'is\n', '\t\tbest\r']
 
# printing list
print("The original list : " + str(test_list))
 
# Remove trailing / leading special characters from strings list
res=[]
for i in test_list:
    res.append("".join(i.split()))
# Printing result
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))
 
# remove trailing/leading special characters using regex
res = [re.sub(r'^[^A-Za-z0-9]+|[^A-Za-z0-9]+$', '', i) for i in test_list]
 
# Printing result
print("List after removal of special characters : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
 
 
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




# initializing list
test_list = ['\rgfg\t\n', 'is\n', '\t\tbest\r']
# printing list
print("The original list : " + str(test_list))
# Using list comprehensions
res = [x.strip() for x in test_list]
# Printing result
print("List after removal of special characters : " + str(res))
#This code is contributed by Jyothi pinjala.
 
 
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:

  1. If the input list is empty, return an empty list.
  2. Strip leading and trailing special characters from the first element of the list.
  3. Recursively, call strip_list_recursive function on the rest of the list (i.e., all elements except the first).
  4. Combine the stripped first element and the recursive result (i.e., stripped rest of the list) into a new list.
  5. 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
# initializing list
test_list = ['\rgfg\t\n', 'is\n', '\t\tbest\r']
 
# printing list
print("The original list : " + str(test_list))
 
res = strip_list_recursive(test_list)
# Printing result
print("List after removal of special characters : " + str(res))
#this code contributed by tvsk
 
 
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




# initializing list
test_list = ['\rgfg\t\n', 'is\n', '\t\tbest\r']
 
# printing list
print("The original list : " + str(test_list))
 
# Remove trailing / leading special characters from strings list
# Using lambda function with replace() method
res = list(map(lambda x: x.replace('\n', '').replace('\t', '').replace('\r', ''), test_list))
 
# Printing result
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.



Next Article
Remove Special Characters from String in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
  • 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
  • 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
  • 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 | Remove last character in list of strings
    Sometimes, we come across an issue in which we require to delete the last character 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 plus
    8 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
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