Filtering characters from a string

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

First of all, you need to iterate over str1 with a for loop, and then compare with str2 to do the subtraction. I have to create a third line in which the output will be saved, but after that I lost a little.

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

This is what I played with, but I don’t understand how I should act.

+4
source share
2 answers

Just use str.translate() :

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

In the documentation:

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

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

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

 ''.join(c for c in str1 if c not in str2) 
+11
source

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) 
+1
source

Source: https://habr.com/ru/post/1496419/


All Articles