desperate
desperate

Reputation: 19

In python, how to compare two numerical strings without casting them to int()?

For example, to check if they are greater than, lesser than or equal to each other without using int() and def.

num1 = "67"
num2 = "1954"

Upvotes: 2

Views: 849

Answers (2)

user2390182
user2390182

Reputation: 73460

Easiest without padding to an unknown length:

if (len(num1), num1) < (len(num2), num2):
    print(num1, "<", num2)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

Left pad with zero and then compare the strings lexicographically:

num1 = "67"
num2 = "1954"
if num1.zfill(10) < num2.zfill(10):
    print("67 is less than 1954")

Note here that the left padding trick leaves the 2 numbers with the same string length. So we are doing something like comparing 0067 to 1954, in which case the dictionary order is in agreement with the numerical order.

Upvotes: 5

Related Questions