我的代码中有很大的字符串。我想检测字符串之间的不同字符。这是我的意思的一个例子:
a='ababaab'
b='abaaaaa'
a=a-b
print(a)
我希望有点喜欢这些; 'bb'或'000b00b'
我知道听起来很奇怪,但我确实需要这个。
你可以这样做:
a = 'ababaab'
b = 'abaaaaa'
a = ''.join(x if x != y else '0' for x, y in zip(a, b))
# '000b00b'
# OR
a = ''.join(x for x, y in zip(a, b) if x != y)
# 'bb'
这是一个例子:它适用于列表
listA = ["a","b"]
listB = ["b", "c"]
listC = [item for item in listB if item not in listA]
print listC
产量
# ['c']
您可以创建自定义函数,如下所示:(假设两个字符串的长度相等)
def str_substract(str1, str2):
res = ""
for _ in xrange(len(str1)):
if str1[_] != str2[_]:
res += str1[_]
else:
res += "0"
return res
a='ababaab'
b='abaaaaa'
print str_substract(a, b)
输出:
000b00b
result = ''
for temp in a:
result += temp if temp not in b else '0'
使用zip
:
res = ''
for i, j in zip(a, b):
if i == j:
res += '0'
else:
res += i
使用列表存储结果可能更有效。
如果你想要s1 - s2
:
s1 = 'ababaab'
s2 = 'abaaaaa'
for i,j in zip(s1,s2):
if (i != j):
print i,
输出:bb