Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing character in list of strings

Tags:

python

If I have a list of strings such as:

[("aaaa8"),("bb8"),("ccc8"),("dddddd8")...] 

What should I do in order to get rid of all the 8s in each string? I tried using strip or replace in a for loop but it doesn't work like it would in a normal string (that not in a list). Does anyone have a suggestion?

like image 564
user1040563 Avatar asked Nov 26 '11 23:11

user1040563


People also ask

How do I remove special characters from a list of strings?

The str. isalnum() method checks a string for the alphabet or number, and this property is used to remove special characters. The replace() method is used to replace special characters with empty characters or null values.

How do I remove a specific character from a list?

The remove() method is one of the most commonly used list object methods to remove an item or an element from the list. When you use this method, you will need to specify the particular item that is to be removed.

How do I remove unwanted characters from a list in Python?

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

How do I remove a character from a string?

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.


2 Answers

Try this:

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")] print([s.strip('8') for s in lst]) # remove the 8 from the string borders print([s.replace('8', '') for s in lst]) # remove all the 8s  
like image 126
Jochen Ritzel Avatar answered Oct 04 '22 17:10

Jochen Ritzel


Beside using loop and for comprehension, you could also use map

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")] mylst = map(lambda each:each.strip("8"), lst) print mylst 
like image 33
Tg. Avatar answered Oct 04 '22 18:10

Tg.