1

I am trying to remove specific characters from items in a list, using another list as a reference. Currently I have:

forbiddenList = ["a", "i"]
tempList = ["this", "is", "a", "test"]
sentenceList = [s.replace(items.forbiddenList, '') for s in tempList]
print(sentenceList)

which I hoped would print:

["ths", "s", "test"]

of course, the forbidden list is quite small and I could replace each individually, but I would like to know how to do this "properly" for when I have an extensive list of "forbidden" items.

Zswide
  • 175
  • 1
  • 1
  • 12
  • I like to do these things with a regex - regex's even have classes which are helpful - (e.g trying to remove all non printable chars) – alex.feigin May 04 '15 at 19:00
  • anyway this is a dup - http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python – alex.feigin May 04 '15 at 19:07

2 Answers2

3

You could use a nested list comprehension.

>>> [''.join(j for j in i if j not in forbiddenList) for i in tempList]
['ths', 's', '', 'test']

It seems like you also want to remove elements if they become empty (as in, all of their characters were in forbiddenList)? If so, you can wrap the whole thing in even another list comp (at the expense of readability)

>>> [s for s in [''.join(j for j in i if j not in forbiddenList) for i in tempList] if s]
['ths', 's', 'test']
Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
  • This is neat and avoids "cheating" with regular expressions where pure list comprehension, as fully supported in python, works fine. – gustafbstrom May 04 '15 at 19:07
1
>>> templist = ['this', 'is', 'a', 'test']
>>> forbiddenlist = ['a', 'i']
>>> trans = str.maketrans('', '', ''.join(forbiddenlist))
>>> [w for w in (w.translate(trans) for w in templist) if w]
['ths', 's', 'test']

This is a Python 3 solution using str.translate and str.maketrans. It should be fast.

You can also do this in Python 2, but the interface for str.translate is slightly different:

>>> templist = ['this', 'is', 'a', 'test']
>>> forbiddenlist = ['a', 'i']
>>> [w for w in (w.translate(None, ''.join(forbiddenlist)) 
...         for w in templist) if w]
['ths', 's', 'test']
Shashank
  • 12,768
  • 4
  • 31
  • 60