Reputation: 21
I'm asked to compare two different string and return the dis-matches. And if one string is longer than another, come out the extra characters.
characters1=list(contents1)
characters2=list(contents2)
for (a,b) in zip(characters1, characters2):
if a != b:
print('Mismatch at character', characters1.index(a), a, '!=', b)
Here is what I have done and I cannot figure out the extra part.
Upvotes: 1
Views: 91
Reputation: 13415
>>> a = "xyz"
>>> b = "abcdef"
>>> a[len(b):] or b[len(a):]
'def'
Also, as @bereal pointed out, characters1.index(a)
won't work as you expect. You could consider using enumerate
:
for i, (a, b) in enumerate(zip(characters1, characters2)):
if a != b:
print('Mismatch at character', i, ':', a, '!=', b)
print('Extra string:', characters1[i+1:] or characters2[i+1:])
Upvotes: 0
Reputation: 34272
I'd use itertools.izip_longest here, something like:
for idx, (a, b) in enumerate(izip_longest(s1, s2)):
if a and b:
if a != b:
print 'Mismatch at {0}: {1} != {2}'.format(idx, a, b)
else:
suffix = (s1 if a else s2)[idx:]
print 'Extra string: {0}'.format(suffix)
break
Notice also that index()
returns the first entrance of the item, so that might return a wrong result if the character repeats in the string. enumerate is the way to go. Converting strings to lists is also redundant, strings are already iterable.
Upvotes: 1
Reputation: 49320
This shows how to compare the two list
s, and will properly compare two different strings of equal length:
a = ['abc', 'def', 'ghi']
b = ['abc', 'ddf', 'ghij']
for x,y in zip(a, b):
if x!=y:
print(x, y, x[len(y):] if len(x)>len(y) else y[len(x):])
Prints:
def ddf
ghi ghij j
Upvotes: 0
Reputation: 10135
Something like this:
if len(characters1) > len(characters2):
print('Extra characters1: ', characters1[len(characters2):])
elif len(characters2) > len(characters1):
print('Extra characters2: ', characters2[len(characters1):])
Upvotes: 0
Reputation: 1834
Compare their length:
if len(a)>len(b):
print("a is longer than b by %s" % str(len(a)-len(b)))
print("Extra part is %s" % a[len(b):])
elif len(a)<len(b):
print("a is shorter than b by %s" % str(len(b)-len(a)))
print("Extra part is %s" % b[len(a):])
Upvotes: 0