3 回答
TA贡献1943条经验 获得超7个赞
您可以zip在这里使用:
def compare(s1, s2):
if len(s1) != len(s2):
return False
else:
for c1, c2 in zip(s1, s2):
if c1 != c2:
return False
else:
return True
>>> compare('foo', 'foo')
True
>>> compare('foo', 'fof')
False
>>> compare('foo', 'fooo')
False
在您的代码中,您将在每次迭代中重置countto的值0:
a = input('Please enter the first string to compare:')
b = input('Please enter the second string to compare: ')
if len(a) != len(b): # match the length first
print ('Strings don\'t match')
else:
count = 0 #declare it outside of while loop
while count < len(a): #loop until count < length of strings
if a[count] != b[count]:
print ('Strings don\'t match! ')
break
count = count + 1
else:
print ("string match")
TA贡献1841条经验 获得超3个赞
您将count在每次循环迭代时将其重置为0。因此,循环会一遍又一遍地比较第一个元素。要解决该问题,只需将count = 0分配移到循环外即可,如下所示:
# ...
b = input('Please enter the second string to compare: ')
count = 0
while True:
if a[count] != b[count]:
# ...
完成此操作后,您将意识到还有第二个问题–到达其中一个字符串的末尾时,程序将崩溃。您可能也想处理这种情况。
TA贡献1795条经验 获得超7个赞
a = raw_input('Please enter the first string to compare:')
b = raw_input('Please enter the second string to compare: ')
count = 0
if len(a) == len(b):
while count < len(a):
if a[count] != b[count]: # code was intended to raise an alarm only after finding the first pair of different elements
print ('Strings don\'t match! ')
break
else: # otherwise the loop goes on to scan the next pair of elements
count = count + 1
else:
print "Strings are not of equal length"
使用raw_input,将count放入while循环之外,并在True ==>时更改while count!= len(a),以防止“ IndexError:字符串索引超出范围”。
添加回答
举报