String Comparison in Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 73:-  String Comparison in Python

In Python, you can compare strings using comparison operators. String comparison is based on lexicographic (dictionary) order, where each character in the string is compared based on its Unicode code point value.

The comparison operators used for string comparison are:

  1. Equality (==): Checks if two strings have the same content.

pythonCopy code

str1 = "hello" str2 = "Hello" print(str1 == str2)   # Output: False

  1. Inequality (!=): Checks if two strings have different content.

pythonCopy code

str1 = "apple" str2 = "orange" print(str1 != str2)   # Output: True

  1. Less than (<) and Less than or equal to (<=): Compares two strings lexicographically.

pythonCopy code

str1 = "apple" str2 = "banana" print(str1 < str2)    # Output: True print(str1 <= str2)   # Output: True

  1. Greater than (>) and Greater than or equal to (>=): Compares two strings lexicographically.

pythonCopy code

str1 = "banana" str2 = "apple" print(str1 > str2)    # Output: True print(str1 >= str2)   # Output: True

Keep in mind that string comparison is case-sensitive, meaning uppercase characters are considered "less than" lowercase characters based on their Unicode values.

If you want to perform case-insensitive string comparison, you can convert both strings to lowercase or uppercase using the lower() or upper() methods before comparing them.

pythonCopy code

str1 = "Hello" str2 = "hello" print(str1.lower() == str2.lower())   # Output: True

It's important to remember that when comparing strings, their contents are compared, not their memory addresses. So even if two strings have the same content but are stored in different memory locations, the comparison will still yield the correct result.

String comparison is a fundamental operation in Python, and it allows you to compare and make decisions based on the contents of strings in your code.

8. String

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support

Sciaku (सियाकु)

Sciaku (सियाकु) provides you a technical and programming content like Java Programming, Python Programming, C Programming,Android Development, Web Development, etc. Learn how to make software, website, and applications here and also we have industrial internship for you.

Contact

G20, Gopal Vihar Colony, Noida Sector 2, Uttar Pradesh, India, 201301

info@sciaku.com

Copyright © 2022-2025 Created by ❤️ Sciaku

Privacy Policy | Terms & Conditions | Refunds Policy