Python中不使用int()转换且不定义def函数,如何比较两个数值字符串的大小关系?
Let's work through this problem directly—no fancy functions or type conversion allowed, just plain Python string logic. Let's use your example values to walk through the solution:
num1 = "67" num2 = "1954"
First, leverage string length for quick checks
For positive integer strings, length tells us a lot right away: a longer string always represents a larger number (since we're dealing with base-10 digits). So we start here:
if len(num1) > len(num2): print(f"{num1} is greater than {num2}") elif len(num1) < len(num2): print(f"{num1} is less than {num2}")
If lengths match, compare digit-by-digit
When the strings are the same length, we can compare individual characters directly. Numeric characters have sequential ASCII values (e.g., '0' < '1' < ... < '9'), so we don't need to convert them to numbers to know their order:
else: # Iterate through each pair of digits for d1, d2 in zip(num1, num2): if d1 > d2: print(f"{num1} is greater than {num2}") break elif d1 < d2: print(f"{num1} is less than {num2}") break else: # The loop finished without breaking—all digits are identical print(f"{num1} is equal to {num2}")
Full working code for your example
Putting it all together, here's the complete snippet that will correctly evaluate your test case:
num1 = "67" num2 = "1954" if len(num1) > len(num2): print(f"{num1} > {num2}") elif len(num1) < len(num2): print(f"{num1} < {num2}") else: for d1, d2 in zip(num1, num2): if d1 > d2: print(f"{num1} > {num2}") break elif d1 < d2: print(f"{num1} < {num2}") break else: print(f"{num1} == {num2}")
Running this will output 67 < 1954, which is exactly what we expect.
Quick notes
- This assumes your input strings are positive integers (no negative signs, decimals, or leading zeros). If leading zeros are possible, you'd want to add a quick cleanup step like
num1 = num1.lstrip('0') or '0'to handle cases like "0067" vs "67". - The
elseattached to theforloop is a handy Python trick—it only runs if the loop completes without hitting abreak, meaning every digit matched perfectly.
内容的提问来源于stack exchange,提问作者desperate

