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

如何通过循环动态匹配正确的英文序数词后缀(st/nd/rd/th)?

Fixing Ordinal Suffix Matching in Python

Got it, let's get that ordinal suffix logic working right! The main issues with your current code are that it doesn't handle the 11-13 exceptions correctly (those always use "th" no matter their last digit) and the number variable's scope is messed up—your conditionals are outside the loop, so they only look at the last number in your range.

First, let's lay out the clear rules for English ordinal suffixes:

  • Numbers ending in 1 (but not 11, 111, etc.) use "st"
  • Numbers ending in 2 (but not 12, 112, etc.) use "nd"
  • Numbers ending in 3 (but not 13, 113, etc.) use "rd"
  • Every other number (including 11,12,13 and all numbers ending in 4-0) use "th"

Here's a clean, reliable implementation:

def get_ordinal_suffix(number):
    # Catch the 11-13 exceptions first—they always get "th"
    if 11 <= number % 100 <= 13:
        return "th"
    # Check the last digit for standard suffixes
    last_digit = number % 10
    if last_digit == 1:
        return "st"
    elif last_digit == 2:
        return "nd"
    elif last_digit == 3:
        return "rd"
    # All other cases fall to "th"
    return "th"

# Test with your range from 1 to 113
for number in range(1, 114):
    suffix = get_ordinal_suffix(number)
    print(f"{number} is the {number}{suffix} number.")

Why this works:

  • We first check if the number's last two digits are 11-13—this covers all edge cases like 11, 111, 213 that should use "th" instead of their single-digit suffix.
  • Using a function makes this logic reusable, so you can grab the suffix for any number anytime without rewriting code.
  • The f-string in the print statement makes the output clean and easy to read.

If you run this, you'll see exactly what you wanted: 11 becomes "11th", 111 becomes "111st", 112 becomes "112nd", 113 becomes "113rd", and all other numbers follow the rules correctly.

Your original code had a few missteps:

  • The conditionals were outside the for loop, so they only ran once for the last number (113) instead of every number in the range.
  • The or not ex1 checks didn't serve any purpose (since ex1 is 11, not ex1 is False, so those conditions never triggered).
  • You repeated logic for checking the exact number vs the last digit, which made the code confusing to follow.

This solution fixes all those issues and is straightforward to tweak if you ever need to adjust the rules!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:19:01