You are currently viewing How to Compare Strings in Python

How to Compare Strings in Python

String is one of the most important data types used in programming language. There are a number of ways to compare strings in Python.

String is one of the most important data types used in programming language. There are a number of ways to compare strings in Python.

Method 1: Compare Strings using == Operator

Most commonly, we use the == operator to determine if two strings are equal. If the strings are equal, the operator returns True, otherwise, it returns False.

Code:

txt_1 = "what is your name"
txt_2 = "what is your name"
txt_1 == txt_2

Output:

True

Method 2: Compare Strings using != Operator

You can also use != to compare two strings. The operator ‘!=’ will always return False if the strings are equal and vice versa. Let’s do this coding thing

Code:

txt_1 = "what is your name"
txt_2 = "what is your name"
txt_1 != txt_2

Output:

False

References:

https://docs.python.org/3/

Leave a Reply