python - 如何找到两个字符串中都没有出现的字母?

标签 python

我需要编写代码来打印出所有未出现在两个字符串中的字母。所以基本上我所拥有的恰恰相反。打印出出现在两个字符串中的所有字母。这是代码。我不确定如何更改它。

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/

相关文章:

python - 根据多个groupby计算总和

python - Pandas 在列中找不到元素

python - 如何在kivy中使用RecycleView?

python - 我应该如何在 Bottle 应用程序中使用 sqlalchemy session 来避免 'Lost connection to MySQL server during query'

python - 使用 python SSH 和 telnet 到本地主机

python - joblib.Memory 是线程安全的吗?

python - 如何使用 qmake 在 OSX 10.6 上链接为 .so 而不是 .dylib

Python:在类方法上使用 contextmanager 的意外行为

python - 类和私有(private)变量

python - Django 1.8 : How do I use my first 3rd Party Fork with my current project?