String Comparison with Relational Operators in Python 💬⚖️
In Python, you can compare strings using relational operators (<, <=, >, >=, ==, !=). These comparisons are based on lexicographical (dictionary) order, which uses the Unicode code points of the characters. 📖
How String Comparison Works 🤔
- Character-by-character comparison: Python compares strings character by character from left to right. ➡️
- Unicode values: Each character is compared based on its Unicode code point value. 🔢
- Case sensitivity: Uppercase letters have lower Unicode values than lowercase letters (‘A’ is 65, ‘a’ is 97). 🔡
- Length matters: If all characters are equal, the shorter string is considered smaller. 📏
Examples 💡
Python
# Equality comparisons
print("hello" == "hello") # True ✅
print("Hello" == "hello") # False (case matters) ❌
print("hello" != "world") # True ✅
# Lexicographical comparisons
print("apple" < "banana") # True ('a' comes before 'b') ✅
print("apple" > "banana") # False ❌
print("apple" <= "apricot") # True ('p' < 'r') ✅
# Case sensitivity
print("Apple" < "apple") # True (uppercase comes before lowercase) ✅
print("Zebra" < "apple") # True (all uppercase before lowercase) ✅
# Different length strings
print("hi" < "hello") # False ('i' > 'e') ❌
print("hi" < "high") # True (shorter string when prefixes match) ✅
Important Notes 📌
- ASCII/Unicode Order:
- Digits (0-9) < Uppercase letters (A-Z) < Lowercase letters (a-z) 🔢🅰️🔡
- Special characters have their own positions in the Unicode table. ✨
- Case-insensitive comparison: To compare strings ignoring case, convert both to the same case first: ⬇️Python
print("Hello".lower() == "hello".lower()) # True ✅ - Locale-aware comparison: For language-specific sorting, use the
localemodule or special string comparison functions. 🌍 - Performance: String comparison is O(n) where n is the length of the shorter string. ⏱️
String comparison is fundamental for sorting algorithms, searching operations, and many other common programming tasks in Python. 🚀
Bitwise Operators in Python 🧮
Bitwise operators perform operations on integers at the binary level by manipulating individual bits. Here are all the bitwise operators available in Python with examples:
1. Bitwise AND (&) 🤝
Performs a logical AND on each pair of corresponding bits.
Python
a = 10 # 1010 in binary
b = 4 # 0100 in binary
print(a & b) # 0 (0000 in binary)
2. Bitwise OR (|) ➕
Performs a logical OR on each pair of corresponding bits.
Python
a = 10 # 1010
b = 4 # 0100
print(a | b) # 14 (1110)
3. Bitwise XOR (^) 🔀
Performs a logical exclusive OR on each pair of corresponding bits.
Python
a = 10 # 1010
b = 4 # 0100
print(a ^ b) # 14 (1110)
4. Bitwise NOT (~) 🔄
Inverts all the bits (unary operator). Note that this gives the two’s complement.
Python
a = 10 # 1010
print(~a) # -11 (inverts bits and adds 1 for two's complement)
5. Left Shift (<<) ⬅️
Shifts bits to the left, filling with 0s on the right.
Python
a = 10 # 1010
print(a << 1) # 20 (10100)
print(a << 2) # 40 (101000)
6. Right Shift (>>) ➡️
Shifts bits to the right, filling with 0s on the left (for positive numbers).
Python
a = 10 # 1010
print(a >> 1) # 5 (0101)
print(a >> 2) # 2 (0010)
Practical Examples 💡
- Check if a number is even or odd:Python
num = 15 if num & 1: print("Odd") else: print("Even")✅ - Swap two numbers without temporary variable:Python
a = 5 b = 7 a = a ^ b b = a ^ b a = a ^ b print(a, b) # 7 5🔄 - Check if two numbers have opposite signs:Python
x = 10 y = -5 if (x ^ y) < 0: print("Opposite signs") else: print("Same sign")↔️ - Multiply/Divide by powers of 2:Python
num = 20 print(num << 1) # Multiply by 2 (40) print(num >> 1) # Divide by 2 (10)✖️➗
Important Notes 📌
- Bitwise operators work on integers only. 🔢
- The results depend on how numbers are represented in binary (two’s complement for negative numbers). 💻
- Left shifting is equivalent to multiplying by 2n. 📈
- Right shifting is equivalent to integer division by 2n. 📉
- Bitwise operations are generally faster than arithmetic operations. ⚡
Bitwise operators are commonly used in:
- Low-level programming 🖥️
- Embedded systems 🤖
- Cryptography 🔐
- Compression algorithms 🤏
- Network protocols 🌐
- Performance-critical code sections 🚀
Chaining Comparisons in Python 🔗⚖️
Python allows you to chain multiple comparison operations in a single expression, making your code more concise and readable. This feature is sometimes called “comparison operator chaining” or “range comparisons.” 📏
How Chained Comparisons Work 🤔
When you chain comparisons, Python automatically combines them with logical and operators. The expression a < b < c is equivalent to a < b and b < c, but more efficient because b is only evaluated once. ⚡
Basic Syntax:
Python
x < y < z
This is equivalent to:
Python
x < y and y < z
Examples 💡
Numeric Range Checking 🔢
Python
age = 25
# Traditional way
if 18 <= age and age <= 65:
print("Eligible")
# With chained comparisons
if 18 <= age <= 65:
print("Eligible") # Output: Eligible
Multiple Comparisons 🧩
Python
x = 5
# Check if x is between 1 and 10 but not 7
if 1 <= x <= 10 and x != 7:
print("Valid number") # Output: Valid number
# Can be written as (though less readable and subtly different if x is modified within an expression):
# if 1 <= x != 7 <= 10:
# print("Valid number") # Works but less readable
String Comparisons 💬
Python
name = "Bob"
if "A" <= name <= "M":
print("Name is in first half of alphabet") # Output: Name is in first half of alphabet
Combining Different Operators 🔄
Python
temperature = 22.5
if 20 <= temperature <= 25:
print("Comfortable room temperature") # Output: Comfortable room temperature
Important Notes 📌
- Evaluation Order: Comparisons are evaluated from left to right. ➡️Python
a < b < c # Evaluates as (a < b) and (b < c) - Short-Circuiting: Like regular boolean expressions, chained comparisons short-circuit. ⚡Python
# If the first comparison fails, the second isn't evaluated result = 1 > 2 > some_function() # some_function() never gets called if 1 > 2 is False - All Operators Don’t Need to Be the Same: You can mix and match.Python
if 1 < x <= 10: pass if a == b == c: pass if x != y != z: pass - Performance Benefit: In
a < b < c,bis only evaluated once, whereas ina < b and b < c,bmight be evaluated twice ifa < bis true. 🚀
Advanced Examples 💡
Multiple Variables 📊
Python
a, b, c = 1, 2, 3
if a < b < c:
print("Increasing sequence") # Output: Increasing sequence
With Functions ⚙️
Python
def is_positive(x):
return x > 0
if is_positive(5) < is_positive(10): # Evaluates to (True < True) which is (1 < 1) → False
print("This won't print")
In While Loops 🔄
Python
x = 0
while 0 <= x <= 3: # Changed limit for shorter output
print(x)
x += 1
# Output:
# 0
# 1
# 2
# 3
Chained comparisons are particularly useful for range checking and making mathematical conditions more readable. They’re a Pythonic way to write clean, expressive conditions. ✅