Home > other >  Store the character of a string found in another string
Store the character of a string found in another string

Time:01-20

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

CodePudding user response:

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)

CodePudding user response:

I mean in order to get the correct order and capitalization of word1 you probably need to loop over str1, so:

new_str1 = "" 
word1 = ""

for c in str1:
    if c in set(str2):
        word1  = c
    else:
        new_str1  =c

And if capitalization don't matter.

well word1 = set(str2) and

import re

str1 = re.sub("[tsK]","", str1)
    

CodePudding user response:

For short string like str2 the algorithm would not affect the performance and an optimisation would be exaggerating. Still, as it is short you can get rid of the inner loop and use an if statement instead. And you don't need to call lower in each loop. Just call it before entering the for:

word1 = ''
str1 = str1.lower()
for i in str1:
if i == "t" or i == "s" or i == "k":
    word1  = i
    str1 = str1.replace(i,'')
        

This should be way faster as the other letters are not tested against once one condition has evaluated to true.

And as @jarmod said, no need to convert a str to list, as str is iterable.

EDIT: for a case sensitive letters in word1, you need to use a temp variable:

word1 = ''
str1_low = str1.lower()
count = 0
for i in str1_low:
    count = count   1
    if i == "t" or i == "s" or i == "k":
        word1  = str1[count]
        str1 = str1[:count]   str1[count 1:]
  •  Tags:  
  • Related