katja92 katja92 - 2 years ago 103
Python Question

how to find letters that don't occur in either string?

I need to write code that prints out all letters that don't appear in either of the two strings. So basically what I have does the opposite. Prints out all the letters that occur in both strings. Here is the code. I'm not sure how to change it.

s1 = input('Enter a string:\n')
s2 = input('Enter second string:\n')
s1 = set(s1)
s2 = set(s2)

def notInother(s1, s2):
chars = []
for char in (s1,s2):
if char not in s2:
if char not in s1:

Answer Source

First, you can merge two sets with |, then do - to get all letters from the alphabet with the ones in the string removed:

>>> from string import ascii_letters
>>> set(ascii_letters) - (s1 | s2)
{'e', 'f', 'g', 'h', 'i', 'j', 'k', ...}

You might want to take a look at set operations to save yourself the mess of writing loops.

With for loop:

>>> from string import ascii_letters

>>> def notInother(s1, s2):
...     chars = []
...     for char in ascii_letters:
...         if (char not in s1) and (char not in s2):
...             chars.append(char)
...     return chars
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download