Home > other >  Finding elements not in a string present in another string in python [duplicate]
Finding elements not in a string present in another string in python [duplicate]

Time:10-04

Python. Str1="acddeffg" Str2="fgfdeca"

I want to obtain the letter/s that are in Str1 not present in Str2 and viceversa. in this example is Np1="", Np2="d"

`Str1="abcdefffg"
`Str2="aabcdef"

Answer= Np1="a", Np2="ffg"

CodePudding user response:

You can try this:

Np1 = ''.join([letter for letter in Str1 if letter not in Str2])

Np2 = ''.join([letter for letter in Str2 if letter not in Str1])

CodePudding user response:

Re-reading your question, you probably want to do this:

str1 = "abcdefffg"
str2 = "aabcdef"

def find_diff(left, right):

    l = list(left)
    for letter in right:
        if letter in l:
            l.remove(letter)
    
    return "".join(l)
    
print(find_diff(str1, str2))  # ffg
print(find_diff(str2, str1))  # a

Original answer: You could use sets to get the difference between used letters (ignoring duplicates). Not what the OP is looking for (second example) but I will leave it here for reference.

letters1 = set("abcdefffg")
letters2 = set("aabcdef")

print(letters1 - letters2)  # {'g'}
print(letters2 - letters1)  # set()
  • Related