12

I need to make a function that takes two strings as imnput and returns a copy of str 1 with all characters from str2 removed.

First thing is to iterate over str1 with a for loop, then compare to str2, to accomplish subtraction I should create a 3rd string in which to store the output but I'm a little lost after that.

def filter_string(str1, str2):
    str3 = str1   
    for character in str1:
       if character in str2:
           str3 = str1 - str2
    return str3

This is what I've been playing with but I don't understand how I should proceed.

SunshineTS
  • 125
  • 1
  • 1
  • 6

2 Answers2

30

Just use str.translate():

In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'

From the documentation:

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

If -- for educational purposes -- you'd like to code it up yourself, you could use something like:

''.join(c for c in str1 if c not in str2)
Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • This works and I understand how but I don't think it was strictly how I was supposed to achieve it. – SunshineTS Aug 12 '13 at 02:20
  • 3
    In Python3 the translate function only takes one argument, see https://docs.python.org/3/library/stdtypes.html?highlight=translate#str.translate . To do the same thing in Python 3 you need to do: `'abcdefabcd'.translate(str.maketrans({'a': None, 'c': None, 'd': None}))` , see also https://stackoverflow.com/questions/41535571/how-to-explain-the-str-maketrans-function-in-python-3-6 – asmaier Aug 15 '19 at 14:52
  • This is for Python2. for python3: `text = text.translate(str.maketrans('','',string.punctuation))` – Dhruv Mar 07 '21 at 20:34
6

Use replace:

def filter_string(str1, str2):
    for c in str2:
        str1 = str1.replace(c, '')
    return str1

Or a simple list comprehension:

''.join(c for c in str1 if c not in str2)
Konstantin
  • 2,885
  • 3
  • 22
  • 23
lecodesportif
  • 10,737
  • 9
  • 38
  • 58