我需要编写代码来打印出所有未出现在两个字符串中的字母。所以基本上我所拥有的恰恰相反。打印出出现在两个字符串中的所有字母。这是代码。我不确定如何更改它。
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:
chars.append(char)
print(chars)
最佳答案
首先,您可以使用 |
合并两个集合,然后执行 -
以获取字母表中的所有字母并删除字符串中的字母:
>>> from string import ascii_letters
>>> set(ascii_letters) - (s1 | s2)
{'e', 'f', 'g', 'h', 'i', 'j', 'k', ...}
您可能想看看 set operations避免编写循环的困惑。
使用 for 循环:
>>> 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
关于python - 如何找到两个字符串中都没有出现的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831119/