Compare strings in Python [exact match, partial match, etc.]
This article describes how to compare strings str in Python.
- Exact match [equality comparison]: ==, !=
- Partial match: in, not in
- Forward / Backward match: startswith[], endswith[]
- Order comparison: =
- Case-insensitive comparison: upper[], lower[]
- Regular expressions: re.search[], re.fullmatch[]
Exact match [equality comparison]: ==, !=
As with numbers, the == operator is used to determine if two strings are equal. If they are equal, True is returned, and if they are not, False is returned.
It is case-sensitive. The same applies to comparisons with other operators and methods. See below for a case-insensitive comparison.
! = returns True if they are not equal, and False if they are equal.
Partial match: in, not in
Use the in operator for partial matches, i.e., whether one string contains the other string.
x in y returns True if x is contained in y [x is a substring of y], False if it is not. If each character of x is contained in y discretely, False is returned.
not in returns True if it is not included, False if it is included.
in and not in are also used to check the existence of elements in a list. See the following article for details.
- in operator in Python [for list, string, dictionary, etc.]
Forward / Backward match: startswith[], endswith[]
Use the string method startswith[] for forward matching, i.e., whether a string starts with the specified string.
- Built-in Types - str.startswith[] Python 3.9.7 documentation
You can also specify a tuple of strings as an argument.
True is returned if the string starts with one of the elements of the tuple, and False is returned if the string does not start with any of them. Note that an error will occur if you specify a list instead of a tuple.
Use the string method endswith[] for backward matching, i.e., whether a string ends with the specified string. Its usage is the same as startswith[].
- Built-in Types - str.endswith[] Python 3.9.7 documentation
Order comparison: =
Strings can be compared with the = operators as well as numbers. They are compared in lexical order.