String comparison

String Comparison in Python

Python provides intuitive operators for comparing strings, enabling efficient and straightforward comparisons based on their Unicode values.

String Comparison Operators

Python supports the following operators for string comparison:

  • <: Less than

  • <=: Less than or equal to

  • >: Greater than

  • >=: Greater than or equal to

  • ==: Equal to

  • !=: Not equal to

How String Comparison Works

String comparison in Python is performed character by character from the start, using the Unicode values of the characters. For example, when comparing text1 = "python" and text2 = "code", Python checks the Unicode values of the first characters:

  • 'p' in text1 has a Unicode value of 112.

  • 'c' in text2 has a Unicode value of 99.

Since 112 > 99, text1 is considered greater than text2, so text1 > text2 returns True.

Unicode vs ASCII

In Python, strings are encoded using Unicode, which supports a vast range of characters from various languages and symbols. In contrast, other languages like C or C++ often use ASCII, which is more limited:

  • ASCII supports 128 characters.

  • Extended ASCII supports 256 characters.

  • Unicode supports a much broader range, accommodating global scripts.

The ord() function in Python returns the Unicode value of a character.

Example:

text1 = "python"
text2 = "code"

print(text1 < text2)   # Output: False
print(text1 <= text2)  # Output: False
print(text1 > text2)   # Output: True
print(text1 >= text2)  # Output: True
print(text1 == text2)  # Output: False
print(text1 != text2)  # Output: True

Detailed Examples

Example 1: Comparing Strings of Different Lengths

When comparing "hello" and "helloworld", Python compares characters until the shorter string ends. Since "helloworld" has additional characters, it is considered greater.

Example:

str1 = "hello"
str2 = "helloworld"

print(str1 < str2)  # Output: True

Example 2: Uppercase vs. Lowercase

Uppercase letters have lower Unicode values than lowercase letters. For example, 'A' has a Unicode value of 65, while 'a' has a Unicode value of 97.

Comparing "Code" and "code":

Example:

str1 = "Code"
str2 = "code"

print(str1 < str2)  # Output: True

Since uppercase 'C' has a lower Unicode value than lowercase 'c', "Code" is considered less than "code".

Popular Posts