How to check if two strings are equal?


Check if two strings are equal in Python

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

https://youtu.be/HCHhHDzi6lQ?si=fyi90HEtVtnYaSG0

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

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')

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')

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.