如何在python中减去2个字符串或列表?

问题描述 投票:2回答:6

我的代码中有很大的字符串。我想检测字符串之间的不同字符。这是我的意思的一个例子:

 a='ababaab'
 b='abaaaaa'
 a=a-b
 print(a)

我希望有点喜欢这些; 'bb'或'000b00b'

我知道听起来很奇怪,但我确实需要这个。

python string list difference subtraction
6个回答
4
投票

你可以这样做:

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'

0
投票

这是一个例子:它适用于列表

listA = ["a","b"]
listB = ["b", "c"]
listC = [item for item in listB if item not in listA]
print listC

产量

# ['c']

0
投票

您可以创建自定义函数,如下所示:(假设两个字符串的长度相等)

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

0
投票
result = ''

for temp in a:
    result += temp if temp not in b else '0'

0
投票

使用zip

res = ''
for i, j in zip(a, b):
     if i == j:
         res += '0'
     else:
         res += i

使用列表存储结果可能更有效。


0
投票

如果你想要s1 - s2

   s1 = 'ababaab'
    s2 = 'abaaaaa'



   for i,j in zip(s1,s2):
        if (i != j):
            print i,

输出:bb

© www.soinside.com 2019 - 2024. All rights reserved.