Python and string comparison

String Comparison in Python (Complete Guide)

In this Python tutorial, let us discuss Python compare strings. We will see various examples of python comparing two strings.

There are 9 methods to compare strings in Python, which are shown below:

  • Using the == operator
  • Using the is operator
  • Using the cmp function
  • Using the strcoll function
  • Using the user-defined method
  • Using the !=
  • Using the SquenceMatcher
  • Using the < operator
  • Using the > operator

Python String Comparison

Here we will see multiple methods to compare two strings in Python. However, let us start with the first method in Python.

Method-1: Using the == operator

You can use the == operator to check if two strings are equal in Python.

string1 = "USA" string2 = "USA" # Compare string1 and string2 for equality if string1 == string2: print("The strings are equal") else: print("The strings are not equal") 

The code defines two string variables string1 and string2, both with the value “USA”. It then checks if the two strings are equal using the == operator.

  • If the two strings are equal, the program will print “The strings are equal”, otherwise it will print “The strings are not equal”. Since the two strings are indeed equal, the output will be “The strings are equal”.
Output: The strings are equal

Method-2: Using the is operator

You can use the is an operator to check if two strings are the same object in memory.

string1 = "United Kingdom" string2 = "UNITED KINGDOM" # Check if string1 and string2 refer to the same string in memory if string1 is string2: print("The strings are the same string") else: print("The strings are not the same string") 

The above code defines two string variables, string1 and string2, with different capitalizations. It then uses the is operator to check if the two strings are the same object in memory.

Output: The strings are not the same string

Method-3: Using the cmp function

The cmp function returns -1 if the first string is less than the second, 0 if they are equal, and 1 if the first string is greater than the second.

def cmp(a, b): return (a > b) - (a < b) string1 = "Brazil" string2 = "Brazil" # Compare string1 and string2 using the cmp() function if cmp(string1, string2) == 0: print("The strings are equal") elif cmp(string1, string2) < 0: print("The first string is less than the second") else: print("The first string is greater than the second") 

The code above defines a cmp() function which takes two arguments and returns 1 if the first argument is greater than the second, -1 if it’s less than the second, and 0 if they are equal.

  • It uses the cmp() function to compare string1 and string2, and prints out a message based on the result.

Method-4: Using the strcoll function

The strcoll function is similar to cmp, but takes into account locale-specific rules for string comparison.

import locale # Set the locale to en_US.UTF-8 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Define two string variables, string1 and string2 string1 = "cafe" string2 = "caff" # Use the strcoll() function to compare string1 and string2 if locale.strcoll(string1, string2) == 0: print("The strings are equal") elif locale.strcoll(string1, string2) < 0: print("The first string is less than the second") else: print("The first string is greater than the second") 

The code above imports the locale module, which provides a way to handle locale-specific data, such as dates, times, and currency formats.

  • The code then sets the locale to en_US.UTF-8 using the setlocale() function. It defines two string variables, string1 and string2, and uses the strcoll() function to compare them.

Python string comparison using the strcoll function

Method-5: Using the user-defined method

We are going to create a function that takes two strings as arguments and returns True if they are equal (case-insensitive) or False otherwise.

# Define a function to compare two strings while ignoring case def string_compare(str1, str2): if str1.lower() == str2.lower(): return True else: return False # Call the string_compare() function with "Canada" and "canada" as arguments result = string_compare("Canada", "canada") # Print the result print(result) 

The above code defines a function string_compare() that compares two strings, str1 and str2 , while ignoring the case. The function returns True if the two strings are equal, ignoring case, and False otherwise.

  • The string_compare() function is called with “Canada” and “Canada” as arguments, and the resulting boolean value is assigned to the result variable. Finally, the value of the result is printed on the console.

Method-6: Using the !=

The != operator is used to check if two values are not equal to each other. In the context of strings, you can use != to check if two strings are not equal to each other.

# Define two strings with the same value string1 = "USA" string2 = "USA" # Compare the two strings for inequality if string1 != string2: # If the strings are not equal, print a message print("The two strings are not equal") else: # If the strings are equal, print a different message print("The two strings are equal") 

In the above code, the != operator is used to check if string1 is not equal to an empty string. Since “hello” is not an empty string, the output of this code would be “The string is not empty”.

Output: The two strings are equal

Method-7: Using the SquenceMatcher

You can use the SequenceMatcher class from the difflib module to compare two strings and find the similarity between them.

# Import the difflib module import difflib # Define two strings to be compared string1 = "apple" string2 = "applesauce" # Create a SequenceMatcher object to compare the strings s = difflib.SequenceMatcher(None, string1, string2) # Get the similarity between the two strings similarity = s.ratio() # Print the similarity to the console print(f"The similarity between the two strings is ") 

The above code imports the difflib module and uses it to compare the similarity of two strings, string1, and string2.

  • A SequenceMatcher object is created with the two strings as arguments, and the ratio() method is called on this object to get the similarity score between the strings. The resulting value is stored in the similarity variable.
  • Finally, the similarity value is printed to the console using an f-string with a precision of 2 decimal places.
Output: The similarity between the two strings is 0.67

In this case, the similarity between “apple” and “applesauce” is 0.67, indicating that the two strings are somewhat similar but not identical.

Method-8: Using the < operator

# Define two string variables name1 = 'Python good' name2 = 'Python is good' # Compare the strings and print the result if name1 < name2: print(name1,'is less than',name2) 

The above code defines two string variables, name1 and name2. It then uses an if statement to compare the two strings using the less-than operator ( < ).

less

Method-9: Using the > operator

The > operator performs a lexicographic (dictionary) comparison between the two strings, meaning that it compares the characters in the strings from left to right and returns True if the first string is greater than the second string.

# Define two string variables name1 = 'Python is good' name2 = 'Python good' # Compare the strings and print the result if name1 > name2: print(name1,'is greater than',name2)
Output: Python is good is greater than Python good

You may also like to read the following Python tutorials.

In this Python tutorial, we learned about, Python compare strings using the following methods:

  • Using the == operator
  • Using the is operator
  • Using the cmp function
  • Using the strcoll function
  • Using the user-defined method
  • Using the !=
  • Using the SquenceMatcher
  • Using the < operator
  • Using the > operator

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

String Equals Check in Python: Using 4 Different Methods

String Equals Check In Python

In programming, string comparison is a fundamental operation used to determine whether two strings are equal.

Suppose you are building an application where you want to find a user using his/her username, the username stored in the database is a string and the keyword to be searched is also a string. So you would have to implement some functionality to detect that both strings are the same. Here comes the string comparison.

In this tutorial, we will learn how to compare strings using four different methods so you can choose any one as per your requirement.

Python String Comparison

In Python, string comparison is basically a process through which we compare the strings character-by-character to check for equality.

We can compare strings using several ways like using ‘==’ operator, ‘!=’ operator, ‘is’ operator and __eq__() function. Let’s look at them one by one.

Python ‘==’ Operator to Check the Equality of Two Strings

Python Comparison operators can be used to compare strings and check for their equality in a case-sensitive manner i.e. uppercase letters and lowercase letters would be treated differently.

Python ‘==’ operator compares the two strings in a character-by-character manner and returns True if both strings are equal, otherwise, it returns False.

s1 = "Python" s2 = "Python" s3 = "Java" print(s1 == s2) print(s1 == s3)

Here we can see that s1 is equal to another string s2 so True is printed to the console, whereas when we compared s1 with s3 we got False.

Python ‘!=’ Operator for String Comparison

Python ‘!=’ operator can also be used to perform a string equals check. Its return value is the opposite of the return value obtained using the ‘=’ operator.

The ‘!=’ operator compares two strings and returns True if the strings are unequal, otherwise, it returns False.

s1 = "Python" s2 = "Python" s3 = "Java" if(s1 != s3): print("s1 is not equal to s3") if(s1 != s2): print("s1 is not equal to s2") else: print("s1 is equal to s2")
s1 is not equal to s3 s1 is equal to s2

Python ‘is’ Operator for String Comparison

Python “is” operator can be used to efficiently check for the equality of two string objects. The “is” operator returns True if the two variables point to the same data object, else, it returns False.

s1 = "Python" s2 = "Python" s3 = "Java" if(s1 is s3): print("s1 is equal to s3") else: print("s1 is not equal to s3") if(s1 is s2): print("s1 is equal to s2") else: print("s1 is not equal to s2")
s1 is not equal to s3 s1 is equal to s2

Python __eq__() Function to perform String Equals Check

Python in-built __eq__() method can be used to compare two string objects. The __eq__() method basically compares two objects and returns a boolean True or False. It returns True if strings are equivalent, otherwise, it returns False.

str1 = "Python" str2 = "Python" str3 = "Java" if(str1.__eq__(str3)): print("str1 is equal to str3") else: print("str1 is not equal to str3") if(str1.__eq__(str2)): print("str1 is equal to str2") else: print("str1 is not equal to str2")
str1 is not equal to str3 str1 is equal to str2

String equals check in Python: Caseless Matching

If we use any of the above methods, they check the equality of strings using case-sensitive comparison. Let’s see with the help of an example.

str1 = "Python" str2 = "PYTHON" if(str1.__eq__(str2)): print("str1 is equal to str2") else: print("str1 is not equal to str2")
str1 is not equal to str2

As seen in the above example, the result turns out to be FALSE, because the comparison is case-sensitive.

So how can we check that strings are equal in a case-insensitive comparison?

In order to have a caseless string comparison, i.e. in a case-insensitive manner, we can use the Python string.casefold() function.

The string.casefold() function converts the string to lowercase instantly. It returns a casefolded copy of the string which can be used for caseless matching.

In this scenario of string comparison, we can pass both the input strings to the casefold() function. After which both the string will be converted to lowercase and thus, we can have a caseless comparison.

str1 = "Python" str2 = "PYTHON" str3 = "PYthoN" if((str1.casefold()).__eq__(str2.casefold())): print("str1 is equal to str2") else: print("str1 is not equal to str2") if((str1.casefold()) == (str3.casefold())): print("str1 is equal to str3") else: print("str1 is not equal to str3")
str1 is equal to str2 str1 is equal to str3

Conclusion

In this tutorial, we learned how to compare one string with another string in Python using four methods, and we have also implemented a case-insensitive approach to check string equality. The method mostly used by developers is the ‘==’ operator as it is very simple to implement and does the required job well. Hope you enjoyed reading our content.

References

Источник

Читайте также:  HTML Frames
Оцените статью