×

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python.

So, before that, let’s have a quick revision on “What are strings?”

Strings are a sequence of characters that are denoted using inverted commas ''. They are immutable which means they cannot be changed once declared. The distinction between the two strings can be understood using id().

Examples of a string are-

a=’Bill Gates’
x=’Moscow’

In the first example, we will see how we can compare two strings in Python using relational operators.

We have used the following relational operators in our program-

  1. == - This relational operator is used to compare whether the given two values are equal or not. For example, if we provide the value 2 to variables a and b and then check whether they are equal or not using ‘==’, it will display the result as True, in case of dissimilar values, the result is False.
  1. >,< - These relational operators are used to denote the greater or the smaller value. For example, a>b means a is greater than b, and a<b means a is less than b. On providing values a=3 and b=4 when these operators are applied then, a>b will display the result as False whereas a<b will display the result as True.
  1. != - This relational operator stands for ‘not equal to’. For example, if the values of a and b are 2 and if we apply a!=b, it will display the result as ‘False’ because both the values are equal whereas if a and b hold different values then it will give the result as True.

Following program illustrates how the user has provided two strings and then they are compared using relational operators.

#using relational operator
a="Tutorials"
b="tutorials"
print(a==b)
print(a>b)
print(a<b)
print(a!=b)

INPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

OUTPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

In the output, we can observe that the expected results are displayed after the comparison.

The second example is based on the same idea but here instead of two we have provided four strings.

The four strings are – “Python”, “interesting”, “programming”, “Language”. In the program given below, we have compared str1 with str2 and str3 and str4.

You can try and compare str1 with the other strings as well.

Let us see what happens when we execute the given program-

#using relational operators
str1="Python"
str2="interesting"
str3="programming"
str4="language"
print(str1==str2)
print(str3==str4)
print(str1>str2)
print(str1<str2)
print(str3>str4)
print(str3<str4)

INPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

OUTPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

In the output, we can observe the expected results are displayed when str1 is compared with str2 and str3 is compared with str4.

In the next method of comparing strings, we will see how the two keywords 'is' and 'is not in Python help us to proceed on our objective.

In the given program, we have assigned the string values to objects a and b and then compared them using these keywords.

The next thing that we did in the program was assign the value of a to c and then printed their addresses and after that, we compared all the three objects a,b and c.

The following program illustrates the same.

Let’s see what happens when we execute it!

#using is and is not operator
a="Tutorials"
b="tutorials"
print(a is b)
print(a is not b)
c=a
print(id(a))
print(id(c))
print(a is c)
print(b is c)
print(a is not c)
print(b is not c)

INPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

OUTPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

In the output, we can observe the following things-

  1. The result is displayed based on the comparison of and b.
  2. The addresses come out to be the same because in Python similar values point to a common address.
  3. Then the results based on the comparison of a,b and c are displayed.

The second example is based on the same method but here we have taken three strings str1, str2, and str3 respectively.

We have assigned the string values to the objects str1, str2 and str3 and then compared them using the keywords ‘is’ and ‘is not’.

The next thing that we did in the program was assign the value of str2 to str4 and then printed their addresses and after that, we compared all the four objects str1,str2,str3, and str4.

The following program illustrates the same.

Let’s see what happens when we execute it!

#using relational operators
str1="Python"
str2="interesting"
str3="programming"
print(str1 is str2)
print(str1 is not str2)
print(str1 is str3)
print(str2 is str3)
str4=str2
print(id(str2))
print(id(str4))
print(str2 is str4)
print(str1 is str4)
print(str1 is not str4)
print(str2 is not str4)

INPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

OUTPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

In the output, we can observe the following things-

  1. The result is displayed based on the comparison of str1,str2, and str3.
  2. The addresses come out to be the same because in Python similar values point to a common address.
  3. Then the results based on the comparison of str1,str2,str3, and str4 are displayed.

In our last example of this article, we have defined a function that takes the length of the string as its range, checks whether the index of each element lies within it and if the condition is fulfilled, the declared counters c1 and c2 are incremented.

Once the function is defined, we call the function by passing strings as the parameters.

Following program illustrates the same.

#defining function 
def str_comp(str1,str2):
    c1=0
    c2=0
    for i in range(len(str1)):
        if str1[i]>="0" and str1[i]<="9":
            c1+=1
    for i in range(len(str2)):
        if str2[i]>="0" and str2[i]<="9":
            c2+=1
    return c1==c2
print(str_comp("Tutorials","tutorial"))
print(str_comp("Examples","example09"))
print(str_comp("Python","python90"))

INPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

OUTPUT-

HOW TO COMPARE TWO STRINGS IN PYTHON?

Since the function returns whether the strings are equal or not, in the output we can see the expected results.

So, in this article, we discussed various methods of comparing strings in Python.


Related Topics

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

IPython Display

A command shell, often known as IPython is a software application that makes an operating system's features accessible to users or other applications. Based on the purpose and specific functioning...

6 minutes read.

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python sklearn train_test_split

Sklearn: One of the most beneficial open-source libraries for learning algorithms in Python is, without a doubt, Sklearn or Scikit-Learn. The most effective tools for statistical modeling and machine learning are all included in...

6 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.