ItsMyCode |
In Python the strings are compared with == and != operators. These operators compare if the two given strings are equal or not and return true or false based on the condition.
Python Compare Strings
When you are working in Python, you will often come across scenarios where you need to compare two strings. Let’s take a scenario of a registration page where we need to compare if the entered email id exists in the database or the password and confirm password fields match. You will validate the input by comparing the two strings in Python.
The == and != Operators
The == ( equals ) and != ( not equals ) are the fundamental operators used in string comparison. They work the same way as with integer and float comparisons.
The == (equals) operator returns true if the two string matches with each other otherwise it returns false.
The != (not equals) operator returns true if there is no match between two strings otherwise, it returns false.
Example of == and != Operators
email = 'no-reply@itsmycode.com'
given_email= input('Enter email: ')
if given_email==email:
print('The email is verified with Database')
else:
print(" Email does not exists")
Output
Enter email: no-reply@itsmycode.com
The email is verified with Database
username= 'admin'
given_username=input('Enter username: ')
if(given_username!=username):
print('Valid Username, Proceed with registration')
else:
print('You cannot use this username, select another one')
Output
Enter username: admin
You cannot use this username, select another one
The “is” and “ is not ” Operators
The == and is operators looks the same, but it’s different. The == operator compares two variables based on the actual value stored and returns true or false, whereas the is operator compares two variables based on the object id and returns true or false. The same goes with != and is not operator.
str1= "ItsMyCode"
str2= "ItsMyCode"
str3= str1
print('ID of str1 is ', hex(id(str1)))
print('ID of str2 is ', hex(id(str2)))
print('ID of str3 is ', hex(id(str3)))
print(str1 is str2)
print(str1 is str3)
print(str2 is str3)
Output
ID of str1 is 0x1a340cd7530
ID of str2 is 0x1a340cd7530
ID of str3 is 0x1a340cd7530
True
True
True
If you look at the above example, the str1 , str2 and str3 hold the same value, and when you get the hex value, all the variables have the same value. Python refers to these variables to the same object to better optimizing memory usage.
Since all the variables have the same object ID, Python returns it as true when comparing these variables with is operator. If any of the object ID changes, then it will return false.
The post Python Compare Strings: A Step-By-Step Guide appeared first on ItsMyCode.
Top comments (0)