Python Programming Examples Tutorial Index
Python String Programs

This tutorial demonstrates Python programs for comparing strings. The purpose of this tutorial is to explain to beginners how to use the different comparison operators with conditional statements.

What Is String Comparison in Python?

String comparison in Python is the process of comparing two strings to check if they are equal or not. In Python, you can compare two strings using the == operator. If the strings are the same, the comparison returns True. If the strings are different, the comparison returns False.

Python Program to Compare Strings Using the == (Equal) Operator.

Example Program:

string1 = "hello"
string2 = "world"

if string1 == string2:
    print("The strings are equal.")
else:
    print("The strings are not equal.")

The above python program will output "The strings are not equal." because the two strings are different.

You can also use the == operator to compare strings stored in variables from user input like this:

Example Program:

string1 = input("Enter a string: ")
string2 = input("Enter another string: ")

if string1 == string2:
  print("The strings are equal.")
else:
  print("The strings are not equal.")

The above python program will prompt the user to enter two strings and compare them using the == operator. If the strings are equal, it will print "The strings are equal". If the strings differ, it will print "The strings are not equal".

Python Program to Compare Strings Using the != (Not Equal) Operator.

You can also use the != operator to check if two strings are not equal, like this:

Example Program:

string1 = "hello"
string2 = "world"

if string1 != string2:
    print("The strings are not equal.")
else:
    print("The strings are equal.")

The above python program will output "The strings are not equal."

You can also use the < and > operators to compare the lexicographic order of the strings, meaning that you can compare the strings based on the order of their characters in the ASCII or Unicode table. For example:

Example Program:

string1 = "hello"
string2 = "world"

if string1 < string2:
    print("string1 comes before string2 lexicographically.")
else:
    print("string2 comes before string1 lexicographically.")

The above python program will output "string1 comes before string2 lexicographically."

Keep in mind that when comparing strings, the comparison is case-sensitive. For example, the strings "hello" and "Hello" are not equal. If you want to compare strings in a case-insensitive way, you can convert both strings to lowercase or uppercase using the lower() or upper() method before comparing them.