If I have a list of strings such as:
[(\"aaaa8\"),(\"bb8\"),(\"ccc8\"),(\"ffffdffffd8\")...]
What should I do in order to get rid of all the
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
lst = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")...]
msg = filter(lambda x : x != "8", lst)
print msg
EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.
Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.
To make this (kinda work?) with how the intent of the question was we could perform something similar to this
msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].
This would result in a data type that looks like this
msg = [["a", "a", "a", "a"], ["b", "b"]...]
So finally to wrap that up we would have to map it to bring them all back into the same type roughly
msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))
I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.
Try this:
lst = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
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
mylist = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
print mylist
j=0
for i in mylist:
mylist[j]=i.rstrip("8")
j+=1
print mylist
Here's a short one-liner using regular expressions:
print [re.compile(r"8").sub("", m) for m in mylist]
If we separate the regex operations and improve the namings:
pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res
A faster way is to join the list, replace 8 and split the new string:
mylist = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
mylist = ' '.join(mylist).replace('8','').split()
print mylist