+ 4

How to compare two strings in python3

29th Nov 2020, 8:56 AM
Purushottam Rai
Purushottam Rai - avatar
4 Answers
+ 6
a simple string comparison can be done with the == operator. print("hello world" == "hello world") will return True print("hello world!" == "helloworld!" will return False In this case we can start a character by character comparison that gives us the first match that is not equal. txt1 = "hello world!" txt2 " "helloworld!" for pos, cmp in enumerate(zip(txt1,txt2)): if cmp[0] != cmp[1]: print(f"position: {pos} with: {repr(cmp[0])} - {repr(cmp[1])}") break
29th Nov 2020, 3:53 PM
Lothar
Lothar - avatar
+ 3
Strings in python are compared lexicographically, which allows you to use the normal comparison operators (==, !=, <, >, <=, >=)
29th Nov 2020, 9:01 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Thanks😃
2nd Dec 2020, 2:27 PM
Purushottam Rai
Purushottam Rai - avatar