Something like this?
a = "abcde"
b = "ab2de"
for index, char in enumerate(a):
if not b[index] == char:
print(f"First mismatch on index {index}: {char} is not {b[index]}")
Would print: First mismatch on index 2: c is not 2
Another possibility would be to create a list of 3-way-tuples, where the first element would be the index, the second element would be the char in a and the third element would be the char in b:
a = "abcde"
b = "ab23e"
print([(index, char, b[index]) for index, char in enumerate(a) if not b[index] == char])
Would result in [(2, 'c', '2'), (3, 'd', '3')]
Something like this?
a = "abcde"
b = "ab2de"
for index, char in enumerate(a):
if not b[index] == char:
print(f"First mismatch on index {index}: {char} is not {b[index]}")
Would print: First mismatch on index 2: c is not 2
Another possibility would be to create a list of 3-way-tuples, where the first element would be the index, the second element would be the char in a and the third element would be the char in b:
a = "abcde"
b = "ab23e"
print([(index, char, b[index]) for index, char in enumerate(a) if not b[index] == char])
Would result in [(2, 'c', '2'), (3, 'd', '3')]
Simple Answer
For a -b:
a_diff = [i for i in set(a) if i not in set(b) ]
for b -a:
b_diff = [i for i in set(b) if i not in set(a) ]
Combine the two results to get aggregate diff:
a_diff + b_diff
My output:

Try this:
s1 = 'HELPMEPLZ'
s2 = 'HELPNEPLX'
[i for i in xrange(len(s1)) if s1[i] != s2[i]]
It will return:
> [4, 8]
The above solution will return a list with the indexes in sorted order, won't create any unnecessary intermediate data structures and it will work on Python 2.3 - 2.7. For Python 3.x replace xrange for range.
Python really comes with batteries included. Have a look at difflib
>>> import difflib
>>> a='HELPMEPLZ'
>>> b='HELPNEPLX'
>>> s = difflib.SequenceMatcher(None, a, b)
>>> for block in s.get_matching_blocks():
... print block
Match(a=0, b=0, size=4)
Match(a=5, b=5, size=3)
Match(a=9, b=9, size=0)
difflib is very powerful and a some study of the documentation is really recommended.
Python: Finding the position of the first occurring difference between 2 strings. (Unequal lengths) - Stack Overflow
Python - difference between two strings - Stack Overflow
Comparing two strings and returning the difference. Python 3 - Stack Overflow
python - Finding differences between strings - Stack Overflow
hello friends !
so i have a question in where there are 2 strings
string_1 = "This is the first sentence"
string_2 = "And this is the second sentence"i am trying to find words that are in 1 string thats not in another so the answer to this one will be something like:
['This', 'first', 'And', 'this', 'second']
so this was what i did. it might be janky but i just wanted to try it out myself before i asked around.
string_1 = string_1.split()
string_2 = string_2.split()
list(set(string_1).difference(string_2))however, my output is this:
['first', 'This']
im not really sure as to why itsshowing just these values and not the rest. can someone tell me where i made a mistake perhaps please ?
i was using this as a reference
Encapsulate your test in a try/catch in case of IndexError, which means that the second string is shorter than the first one, which means the two strings differ.
for letter in range(len(string1)):
try:
if string1[letter] != string2[letter]:
print("Strings differ at postion {}".format(letter + 1))
break
except IndexError:
print("Strings differ at postion {}".format(letter + 1))
break
Edit: have you thought about the case where string1 is shorter than string2? I think your algorithm will assume both strings are identical.
My solution would be:
def print_first_difference(string1, string2):
aggr_strings = zip(string1, string2)
for index, tup in enumerate(aggr_strings):
if tup[0] != tup[1]:
print("Strings differ at position " + str(index))
break
else:
if len(aggr_strings) != len(max(string1, string2)):
print("Strings differ at position " + str(len(min(string1, string2))))
else:
print("Strings are identical")
You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.
A simple example:
import difflib
cases=[('afrykanerskojęzyczny', 'afrykanerskojęzycznym'),
('afrykanerskojęzyczni', 'nieafrykanerskojęzyczni'),
('afrykanerskojęzycznym', 'afrykanerskojęzyczny'),
('nieafrykanerskojęzyczni', 'afrykanerskojęzyczni'),
('nieafrynerskojęzyczni', 'afrykanerskojzyczni'),
('abcdefg','xac')]
for a,b in cases:
print('{} => {}'.format(a,b))
for i,s in enumerate(difflib.ndiff(a, b)):
if s[0]==' ': continue
elif s[0]=='-':
print(u'Delete "{}" from position {}'.format(s[-1],i))
elif s[0]=='+':
print(u'Add "{}" to position {}'.format(s[-1],i))
print()
prints:
afrykanerskojęzyczny => afrykanerskojęzycznym
Add "m" to position 20
afrykanerskojęzyczni => nieafrykanerskojęzyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2
afrykanerskojęzycznym => afrykanerskojęzyczny
Delete "m" from position 20
nieafrykanerskojęzyczni => afrykanerskojęzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
nieafrynerskojęzyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "ę" from position 16
abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7
I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:
import difflib
case_a = 'afrykbnerskojęzyczny'
case_b = 'afrykanerskojęzycznym'
output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']
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.
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)
You could use difflib, and do it like this:
from difflib import Differ
def appendBoldChanges(s1, s2):
"Adds <b></b> tags to words that are changed"
l1 = s1.split(' ')
l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join(['<b>'+i[2:]+'</b>' if i[:1] == '+' else i[2:] for i in dif
if not i[:1] in '-?'])
print appendBoldChanges("britney spirs", "britney sprears")
print appendBoldChanges("sora iro days", "sorairo days")
#Output:
britney <b>sprears</b>
<b>sorairo</b> days
Have a look at the difflib module, you could use a SequenceMatcher to find the changed regions in your text.
a = 'testing this is working \n testing this is working 1 \n'
b = 'testing this is working \n testing this is working 1 \n testing this is working 2'
splitA = set(a.split("\n"))
splitB = set(b.split("\n"))
diff = splitB.difference(splitA)
diff = ", ".join(diff) # ' testing this is working 2, more things if there were...'
Essentially making each string a set of lines, and taking the set difference - i.e. All things in B that are not in A. Then taking that result and joining it all into one string.
Edit: This is a convoluted way of saying what @ShreyasG said - [x for x if x not in y]...
The easiest Hack, credits @Chris, by using split().
Note : you need to determine which is the longer string, and use that for split.
if len(a)>len(b):
res=''.join(a.split(b)) #get diff
else:
res=''.join(b.split(a)) #get diff
print(res.strip()) #remove whitespace on either sides
# driver values
IN : a = 'testing this is working \n testing this is working 1 \n'
IN : b = 'testing this is working \n testing this is working 1 \n testing this is working 2'
OUT : testing this is working 2
EDIT : thanks to @ekhumoro for another hack using replace, with no need for any of the join computation required.
if len(a)>len(b):
res=a.replace(b,'') #get diff
else:
res=b.replace(a,'') #get diff