codescracker


python

Python Program to Compare Two Strings



« Previous Program Next Program »


Compare Two Strings in Python

To compare two strings in python, you have to ask from user to enter any two string to check whether the two string are equal or not as shown in the program given below.

Python Programming Code to Compare Two Strings

Following python program ask from user to enter first and second string to compare the given two string:

# Python Program - Compare Two Strings

print("Enter 'x' for exit.")
string1 = input("Enter first string: ")
if string1 == 'x':
    exit();
else:
    string2 = input("Enter second string: ")
    if string1 == string2:
        print("\nBoth strings are equal to each other.")
        print(string1,"==",string2);
    else:
        print("\nStrings are not equal.")
        print(string1,"!=",string2);

Here is the sample run of the above Python program to demonstrate how to compare two string:

compare two string python

Now enter first string say codescracker and press enter, then again enter the second string say codescracker and again press enter key to check whether codescracker is equal to codescracker or not:

comparing strings program python

Re-run the same program and this time, given first and second string as some unique value say python and first string and java as second string and then press enter to check whether python is equal to java or not:

compare two string program python

Same program on python shell:

python compare two strings

Program Video with Compile and Run

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test