- Use the Relational Operators to Compare Strings in Python
isOperator to Compare Strings in Python
- Use the User-Defined Logic to Compare Strings in Python
- Use the Regular Expressions to Compare Strings in Python
This tutorial will introduce how to compare strings in Python.
Use the Relational Operators to Compare Strings in Python
In Python, the relational operators are used to compare different values. Strings can be compared using these operators. When we compare strings, we compare their Unicode values.
In the code below, we will compare two strings using the relational operators and print their results.
str1 = 'Mark' str2 = 'Jack' print(str1>str2) print(str1<str2) print(str1==str2) print(str1!=str2) print(str1>=str2) print(str1<=str2)
True False False True True False
String comparisons in Python are case-sensitive. In case we want to do the string comparisons in a case-insensitive way, we can use the
islower() function, which converts all the characters in the string to lower case, and then proceed to compare them.
is Operator to Compare Strings in Python
is operator is used to check for identity comparison in Python. This means that if two variables have the same memory location, then their identity is considered the same, and the result of their comparison is
True; otherwise, it is
is operator is different from the
== relational operator since the latter tests for equality. For example,
str1 = 'Mark' str2 = str1 str3 = 'MARK' print(str1 is str2) print(str1 is str3)
Use the User-Defined Logic to Compare Strings in Python
Besides these built-in operators, we can create our user-defined functions to compare strings on other factors like their length and more.
In the following code, we implement a user-defined function to compare the length of two strings.
def check_len(s1,s2): a = len(s1) b = len(s2) if (a>b): print(s1, " is Longer") elif (a == b): print("Equal Length") else: print(s2, " is Longer") str1 = 'Mark' str2 = 'Jack' check_len(str1,str2)
Use the Regular Expressions to Compare Strings in Python
Regular Expressions are very heavily used in Python and can be used to check if a string matches a pattern or not.
In the following example, we will compare two strings with a pattern using regular expressions.
import re str1 = 'Mark' str2 = 'Jack' def check_pattern(s): if re.match("Ma[a-z]+",s): print("Pass") else: print("Fail") check_pattern(str1) check_pattern(str2)
re pattern in the above checks if a string starts with
Ma and is followed by other letters. That is why
Mark returns True, and
ack returns False.