Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to compare string and number in Python?
In Python, you cannot directly compare strings and numbers using comparison operators like <, >, or == because they are different data types. However, there are several approaches to handle string-number comparisons depending on your needs.
Direct Comparison Behavior
Attempting to compare a string and number directly will raise a TypeError in Python 3 ?
# This will raise a TypeError
try:
result = "12" < 100
print(result)
except TypeError as e:
print(f"Error: {e}")
Error: '<' not supported between instances of 'str' and 'int'
Converting String to Number
The most common approach is to convert the string to a number before comparison ?
i = 100
j = "12"
int_j = int(j)
print(int_j < i)
print(f"Comparing {int_j} < {i}: {int_j < i}")
True Comparing 12 < 100: True
Using float() for Decimal Numbers
price = 25.50
price_str = "30.75"
price_float = float(price_str)
print(f"${price} < ${price_float}: {price < price_float}")
$25.5 < $30.75: True
Safe Conversion with Error Handling
Always handle cases where the string might not be a valid number ?
def safe_compare(str_num, number):
try:
return float(str_num) < number
except ValueError:
print(f"'{str_num}' is not a valid number")
return False
# Valid comparison
print(safe_compare("15.5", 20))
# Invalid string
print(safe_compare("abc", 20))
True 'abc' is not a valid number False
Equality Comparison
For equality checks, Python returns False when comparing different types without raising an error ?
num = 42
str_num = "42"
print(f"Direct equality: {num == str_num}")
print(f"After conversion: {num == int(str_num)}")
print(f"Type check: {type(num)} vs {type(str_num)}")
Direct equality: False After conversion: True Type check: <class 'int'> vs <class 'str'>
Comparison Methods Summary
| Method | Use Case | Example |
|---|---|---|
int(string) |
Whole numbers | int("42") < 100 |
float(string) |
Decimal numbers | float("3.14") > 3 |
| Try-except | Safe conversion | Handle invalid strings |
Conclusion
Convert strings to numbers using int() or float() before comparison. Always use try-except blocks for safe conversion when dealing with user input or uncertain data formats.
