Python – Check if Two Strings are Equal

Check if Two Strings are Equal

Two strings are said to be equal, if and only if the two strings have same length and same characters at respective positions.

To check if two strings are equal, we can use Equal-to Comparison Operator. The operator can take two strings as operands, and returns true if the two strings are equal, or false if the two strings are not equal.

Syntax

The syntax of the boolean expression using Equal-to operator to check if the strings str1 and str2 are equal is

str1 == str2
Run

Examples

1. Positive Scenario (Same Strings)

In the following program, we take same string value in str1 and str2 variables, and check if these two strings are equal programmatically.

Python Program

str1 = 'Hello World'
str2 = 'Hello World'

if str1 == str2 :
    print('two strings are equal')
else :
    print('two strings are not equal')
Run

Output

two strings are equal

2. Negative Scenario (Different Strings)

In the following program, we take different string values in str1 and str2 variables, and check if these two strings are equal or not programmatically.

Python Program

str1 = 'Hello World'
str2 = 'Good Morning'

if str1 == str2 :
    print('two strings are equal')
else :
    print('two strings are not equal')
Run

Output

two strings are not equal

Summary

In this tutorial of Python Examples, we learned how to check if two strings are equal using equal-to operator, with the help of well detailed examples.