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

2024-10-03 17:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码中有非常大的字符串。我想检测字符串之间的不同字符。我的意思是:

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

我想是这样的;'bb'或'000b00b'

我知道听起来很奇怪,但我真的需要这个。在


Tags: 字符串代码字符printbbabaaaaaababaab
3条回答

你可以:

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'

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

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)

输出:

^{pr2}$

下面是一个例子:它与列表一起工作

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

输出

^{pr2}$

相关问题 更多 >