13

我正在寻找比较两个字符串并能够作为单独的字符串返回的方法:

  • 所有常见的字符,
  • 不常见的字符,(所有字符,但没有常见字符)
  • 一个字符串唯一的字符。

例子:

A = "123 ABC"
B = "135 AZ"

thingamajigger(A, B)  # would give all these:

intersect = "13 A"  # (includes space)
exclusion = "2BCZ5"
a_minus_b = "2BC"
b_minus_a = "5Z"

a_minus_b很简单......但如果有一种花哨的单线方法可以实现它,那么我很开放。

for i in B:
    A = A.replace(i, "")

这有点像对字符串的布尔运算。

4

1 回答 1

15

使用set

s = set("123 ABC")
t = set("135 AZ")
intersect = s & t # or s.intersection(t)
exclusion = s ^ t # or s.symmetric_difference(t)
a_minus_b = s - t # or s.difference(t)
b_minus_a = t - s # or t.difference(s)
于 2013-07-16T02:22:12.450 回答