[英]How can I subtract 2 string or list in python?
我的代碼中有很大的字符串。 我想檢測字符串之間的不同字符。 這是我的意思的示例:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.