You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:整数转序数词字符串代码异常,所有输出均带th后缀

Fixing Your Ordinal Number Converter Code

Hey there! Let's figure out why your code is only outputting "xxth" every time—great job on writing your first ordinal number converter, by the way! 😊

The Core Issues

Your logic is totally on the right track, but two small bugs are throwing everything off:

  • You're comparing string characters to integers: After converting number to a string, you check conditions like number[-2] == 1. But number[-2] is a string character (e.g., "1" for the number 12), and you're comparing it to the integer 1. These types don't match, so none of your early conditions ever trigger—everything falls through to the final else clause.
  • No safety for single-digit numbers: If someone inputs a single-digit number (like 5), number[-2] will try to access a character that doesn't exist, which would cause an error.

Fixed Code with Explanations

Here's the corrected version, with comments to walk you through each change:

# Get input and convert to integer first
number = int(input('Input a number: '))
# Convert to string for easy digit checking (renamed for clarity)
num_str = str(number)

# First handle numbers where tens digit is 1 (11-19, 111-119, etc.)
# Add a check to make sure the number has at least two digits first
if len(num_str) >= 2 and num_str[-2] == '1':
    ordinal_number = num_str + 'th'
# Now handle single-digit numbers or numbers with non-1 tens digit
elif num_str[-1] == '1':
    ordinal_number = num_str + 'st'
elif num_str[-1] == '2':
    ordinal_number = num_str + 'nd'
elif num_str[-1] == '3':
    ordinal_number = num_str + 'rd'
else:
    ordinal_number = num_str + 'th'

print(ordinal_number)

Key Fixes Breakdown

  1. String-to-string comparisons: We now compare string characters to string literals (like '1' instead of 1), so your conditions will trigger exactly when you want them to.
  2. Single-digit safety: The len(num_str) >= 2 check ensures we only look at the tens digit if the number has two or more digits—no more errors for inputs like 3 or 7.
  3. Clearer variable names: Renamed ordinalnumber to ordinal_number and split the number into number (integer) and num_str (string) to make the code easier to follow as you learn.

Test Cases to Verify

  • Input 31 → 31st (correct, since tens digit is 3, not 1)
  • Input 12 → 12th (correct, tens digit is 1)
  • Input 5 → 5th (correct)
  • Input 2 → 2nd (correct)

内容的提问来源于stack exchange,提问作者FearlessDoggo21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:47:36