比较末尾的特殊字符串

时间:2015-03-13 14:41:11

标签: python string comparison

我有两套

a[i]={'aaa@','bb','ccc@'}
b[j]={'aaa','bb@','ccc@'}

我想将a[i]中的每个字符串与b[j]进行比较,这样如果两个字符串相同并且它们在结尾处有特殊字符,那么它会在上面的列表中打印“相等”,如ccc@如果字符串相等,但其中一个具有特殊字符,则显示“未完全匹配”

2 个答案:

答案 0 :(得分:1)

列表示例:

a=['aaa@','bb','ccc@']
b=['aaa','bb@','ccc@']

index = 0
print "ordered comparison:"
for i,j in zip(a,b):
    if i == j:
        print str(index) + ": Equal"
    elif i.replace("@","") == j.replace("@",""):
        print str(index) + ": Not completely Matched"
    else:
        print str(index) + ": Different"
    index+=1

print "\nunordered comparison:"
for x in a:
    for y in b:
        if x == y:
            print x,y + " are Equal"
        elif x.replace("@","") == y.replace("@",""):
            print x,y + " Not completely Matched"
        else:
            print x,y + " Different"

输出:

enter image description here

答案 1 :(得分:0)

Sets可以轻松地逐个元素进行比较:

>>> a={'aaa@','bb','ccc@'}
>>> b={'aaa','bb@','ccc@'}
>>> c=a.copy()
>>> a-b
set(['aaa@', 'bb'])
>>> a-c
set([])

>>> d={"Product invoice","product verification","product completed@"}
>>> e= {"Product invoice","product verification@","product completed@"}
>>> d-e
set(['product verification'])
>>> d^e
set(['product verification@', 'product verification'])

然后使用空的或非空的truthiness来获得你想要的东西:

>>> 'not matched' if a-b else 'matched'
'not matched'
>>> 'not matched' if a-c else 'matched'
'matched'