简体   繁体   English

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

[英]How can I subtract 2 string or list in python?

I have very large strings in my codes. 我的代码中有很大的字符串。 I would like to detect different characters between the strings. 我想检测字符串之间的不同字符。 Here is an example what I mean: 这是我的意思的示例:

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

I expect kind of like these; 我希望像这样。 'bb' or '000b00b' 'bb'或'000b00b'

I know sounds weird but I really need this. 我知道听起来很奇怪,但我确实需要这个。

You could do: 您可以这样做:

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'

Here is the example: It works wih list 这是示例:它适用于列表

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

Output 产量

# ['c']

You can create custom function as following: (assumption length of both strings are equal) 您可以按以下方式创建自定义函数:(两个字符串的假设长度相等)

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)

output: 输出:

000b00b
result = ''

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

Use zip : 使用zip

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

Using a list to store the result is probably more efficient. 使用列表存储结果可能更有效。

if you want s1 - s2 : 如果要s1 - s2

   s1 = 'ababaab'
    s2 = 'abaaaaa'



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

output : bb 输出: bb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM