Store the character of a string found in another string

I have a string str1 = "This is Kane and Kane is a coder" and another string str2 = "tsk" Now i want to remove all the characters of str2 which are appearing in str1 and store in another variable say word1

The result im expecting is

str1 = "hi i ane and ane i a coder"

word1 = TssKKs

word1 = ''
for i in str2:
    if i in str1.lower():
        word1 += i
        str1 = str1.lower().replace(i,'')

I guess this is not very optimised method as im running a loop for each character of str2 which will affect the time for long strings


Solution 1:

In your example code, for every letter in str2, it needs to iterate over str1 2 times: in the line if i in str1.lower() and in str1.replace(i,''). This means 6 times in in the example.

The following solution only iterates over str1 once and the check against a set is fast. It builds 2 new strings in parallel in one pass.

str1 = "This is Kane and Kane is a coder"
str2 = "tsk"

word = ""
new_str = ""
remove = set(str2)
for letter in str1:
    if letter.lower() in remove:
        word += letter
    else:
        new_str += letter

print(word)
print(new_str)