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 8
s 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?
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With