我的目标是编写一个程序来比较两个字符串并显示前两个不匹配字符之间的差异。
例子:
str1 = 'dog'
str2 = 'doc'
应该返回'gc'
我知道我尝试使用的代码很糟糕,但我希望收到一些提示。这是我解决这个练习的糟糕尝试,它导致我无处可去:
# firstly I had tried to split the strings into separate letters
str1 = input("Enter first string:").split()
str2 = input("Enter second string:").split()
# then creating a new variable to store the result after comparing the strings
result = ''
# after that trying to compare the strings using a for loop
for letter in str1:
for letter in str2:
if letter(str1) != letter(str2):
result = result + letter
print (result)
def first_difference(str1, str2):
for a, b in zip(str1, str2):
if a != b:
return a+b
Usage:
>>> first_difference('dog','doc')
'gc'
但正如 @ZdaR 在评论中指出的那样,结果是未定义的(在本例中None
) 如果一个字符串是另一个字符串的前缀并且长度不同。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)