Python | Remove trailing/leading special characters from strings list

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 : Using map() + str.strip()
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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

 
The original list : ['\rgfg\t\n', 'is\n', '\t\tbest\r']
List after removal of special characters : ['gfg', 'is', 'best']


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.