String Compare in Python
Here you will learn the program code of String Compare in Python Programming.
How to compare strings in python
Python has several ways to compare strings. The most common is the comparison with == and != operators. Another way is using the compare() method, which returns an integer indicating the lexicographical ordering of the strings. Finally, you can use the in operator to check if a substring is found within a string.
Python supports a variety of comparison operators, including == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
Program 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def compare(str1, str2): if len(str1) > len(str2): return 1 elif len(str2) > len(str1): return -1 else: for i in range(len(str1)): if str1[i] > str2[i]: return 1 elif str2[i] > str1[i]: return -1 return 0 #Test the function print(compare('code', 'code')) print(compare('code', 'codeup')) print(compare('codeup', 'code')) |
Output
0
-1
1
Program 2
1 2 3 4 5 6 7 | str1 = "Hello" str2 = "World" if str1 == str2: print("The strings are equal") else: print("The strings are not equal") |
Output
The strings are not equal
Check out our other Python examples