Open In App

String Comparison in Python

Last Updated : 29 Oct, 2024
Comments
Improve
Suggest changes
11 Likes
Like
Report

Python supports several operators for string comparison, including ==, !=, <, <=, >, and >=. These operators allow for both equality and lexicographical (alphabetical order) comparisons, which is useful when sorting or arranging strings.

Let’s start with a simple example to illustrate these operators.


Output
False
True
True

Explanation:

  • == checks if two strings are identical.
  • != checks if two strings differ.
  • <, <=, >, >= perform lexicographical comparisons based on alphabetical order.

Let's explore different methods to compare strings

== Operator for Equality Check

The == operator is a simple way to check if two strings are identical. If both strings are equal, it returns True; otherwise, it returns False.


Output
True

Explanation: In this example, since s1 and s2 have the same characters in the same order, so == returns True.

!= Operator for Inequality Check

The != operator helps to verify if two strings are different. If the strings are different then it will return True, otherwise returns False.


Output
True

Explanation: Here, != checks that s1 and s2 are not the same, so it returns True.

Lexicographical Comparison

Lexicographical comparison checks if one string appears before or after another in alphabetical order. This is especially useful for sorting.


Output
True
True

Explanation: The < and > operators are used to find the order of s1 and s2 lexicographically. This method ideal for sorting and alphabetical comparisons.

Case-Insensitive Comparison

Strings in Python can be compared case-insensitively by converting both strings to either lowercase or uppercase.


Output
True

Explanation: Converting both strings to lowercase (or uppercase) before comparison

Using startswith() and endswith() Methods

The startswith() and endswith() methods in Python are used to check if a string begins or ends with a specific substring.


Output
True
True

Explanation: These methods are helpful for conditional checks based on prefixes or suffixes in a string.

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads