比较两个字符串并返回差异。 Python 3

时间:2015-06-06 13:32:42

标签: python python-3.x

我的目标是编写一个比较两个字符串的程序,并显示前两个不匹配字符之间的差异。

示例:

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)

2 个答案:

答案 0 :(得分:1)

def first_difference(str1, str2):
    for a, b in zip(str1, str2):
        if a != b:
            return a+b

用法:

>>> first_difference('dog','doc')
'gc'

但正如@ZdaR在评论中指出的那样,如果一个字符串是另一个字符串的前缀且长度不同,则结果未定义(在本例中为None)。

答案 1 :(得分:1)

我通过使用单个循环更改了解决方案。

这个怎么样:

# First, I removed the split... it is already an array
str1 = input("Enter first string:")
str2 = input("Enter second string:")

#then creating a new variable to store the result after  
#comparing the strings. You note that I added result2 because 
#if string 2 is longer than string 1 then you have extra characters 
#in result 2, if string 1 is  longer then the result you want to take 
#a look at is result 2

result1 = ''
result2 = ''

#handle the case where one string is longer than the other
maxlen=len(str2) if len(str1)<len(str2) else len(str1)

#loop through the characters
for i in range(maxlen):
  #use a slice rather than index in case one string longer than other
  letter1=str1[i:i+1]
  letter2=str2[i:i+1]
  #create string with differences
  if letter1 != letter2:
    result1+=letter1
    result2+=letter2

#print out result
print ("Letters different in string 1:",result1)
print ("Letters different in string 2:",result2)