Python Is Not Matching a String
Like most programming languages Python allows you to perform comparisons of data values for equality. This includes numbers and strings. However, when comparing complex strings you might find that the strings don't necessarily match even if the appear to do so. In order to check where the difference is you can manually step through the strings to compare them.
Instructions
-
-
1
Take two strings to compare. In this example, one string has an additional space. Other reasons that strings may not compare include hidden newline or tab characters, or mismatched punctuation.
>>>s1 = "hello there " //4 spaces
>>>s2 = "hello there " //5 spaces -
2
Setup up a for loop to run through the longest string. If both strings are not equal in length, then run through the shorter string with a for loop to check if the differences occur within the shorter string:
>>>short
>>>long
>>>if len(s1) >= len(s2):
. . . short = s2
. . . long = s1
. . . else:
. . . short = s1
. . . long = s2
>>>for item in short: -
-
3
Check each string for the length of the shortest string of the two. If a difference between the two occurs within this range, print the index. If not, then the difference occurs simply because the strings are not the same length. If that is the case, then print our the access characters in the longer string:
>>>index = 0
>>>for item in short:
. . . if item != long[index]
. . . print index
. . . index += 1
>>>print long[len(short):len(long]
-
1