Monday, February 10, 2020

Comparing Two Strings in Python

For comparing two strings in Python you can use relational operators (==, <, <=, >, >=, !=). Using these operators content of the Strings is compared in lexicographical order and boolean value true or false is returned.

Note that for equality comparison use ‘==’ not 'is' operator as ‘is’ operator does the identity comparison (compares the memory location of the String objects).

Python String comparison

When Strings are compared in Python, comparison is done character by character.

Checking for equality using ‘==’

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is ',str)
  if str == str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output

String is Python
Strings are equal

In the example using Python string slicing, a slice of the string is obtained which is then compared with another string for equality.

If you use ‘is’ operator, comparison returns false even if the content is same as in that case memory location of the objects is compared.

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is', str)
  if str is str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output


String is Python
Strings are not equal

Python String comparison examples

Let’s see another example with other operators.

def check_equality(str1, str2):
  if str1 > str2:
    print(str1, 'is greater than', str2)

  if str1 < str2:
    print(str1, 'is less than', str2)

  if str1 != str2:
    print(str1, 'is not equal to', str2)

str1 = "This"
str2 = "That"
check_equality(str1, str2)

Output

This is greater than That
This is not equal to That

In the example following condition

if str1 < str2:
  print(str1, 'is less than', str2)

returns false so the message accompanying this condition is not displayed.

That's all for this topic Comparing Two Strings in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Reverse a String
  4. Nonlocal Keyword in Python With Examples
  5. Method Overriding in Python

You may also like-

  1. Name Mangling in Python
  2. Python for Loop With Examples
  3. self in Python
  4. Named Tuple in Python
  5. Switch-Case Statement in Java
  6. Linear Search (Sequential Search) Java Program
  7. Dependency Injection in Spring Framework
  8. Difference Between @Controller And @RestController Annotations in Spring