字符串不在字符串中

时间:2016-09-03 01:15:24

标签: python string python-2.7

所以我有两个字符串

single.phpa = "abc"

现在我正在尝试找到b

中不存在的字符

我的代码是:

b = "ab"

这给大字符串带来了一些错误。我还没有调查过这个错误,但我想知道另一种做同样事情的方法是类似的:

for element in t: 
    if element not in s: 
        print element

上面的代码给我if a not in b: //further code to identify the element that is not in string b 当我运行它时,我不知道如何识别第二个字符串中不存在的元素。

我该怎么做?

1 个答案:

答案 0 :(得分:3)

这是set真正有用的东西:

>>> a = "abc"
>>> b = "abd"
>>> set(a).difference(b)
set(['c'])

这为a中不在b中的项目提供了帮助。如果您想要只显示在其中一个中的项目,可以使用symmetric_difference

>>> a = "abc"
>>> b = "abd"
>>> set(a).symmetric_difference(b)
set(['c', 'd'])

请注意,如果输入正确,您的代码 也应该正常工作:

>>> for element in a:
...     if element not in b:
...         print element
... 
c

但是,如果你正在处理大型序列,那么效率要低得多,而且要编写更多代码,所以我不推荐它。

相关问题