1

My goal is to write a program which compares two strings and displays the difference between the first two non-matching characters.

example:

str1 = 'dog'
str2 = 'doc'

should return 'gc'

I know that the code which I have tried to use is bad but I am hoping to receive some tips. Here is my poor attempt to solve the exercise which leads me to nowhere:

# 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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
oliver oliver
  • 13
  • 1
  • 1
  • 3

2 Answers2

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

Usage:

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

But as @ZdaR pointed out in a comment, result is undefined (in this case None) if one string is a prefix of the other and has different length.

fferri
  • 18,285
  • 5
  • 46
  • 95
4

I changed the solution by using a single loop.

How about this:

# 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)
Youn Elan
  • 2,379
  • 3
  • 23
  • 32