首页 > 解决方案 > 使用循环动态查找序数:find th - st - nd - rd

问题描述

我想动态找到正确的序数根,例如:

111 = 111st
112 = 112nd 
113 = 113rd ...

我尝试了其他解决方案,但找不到好的解决方案。

这是我的代码:

for number in range(1, 114):
    print(number)
    ex1 = 11
    ex2 = 12
    ex3 = 13
    if number == ex1:
        print("is the " + str(number) + "th number.")
    elif number % 10 == 1 or not ex1:
        print("is the " + str(number) + "st number.")
    elif number == ex2:
        print("is the " + str(number) + "nd number.")
    elif number % 10 == 2 or not ex2:
        print("is the " + str(number) + "nd number.")
    elif number == ex3:
        print("is the " + str(number) + "rd number.")
    elif number % 10 == 3 or not ex3:
        print("is the " + str(number) + "rd number")
    else:
        print("is the " + str(number) + "th number.")

标签: pythonpython-3.xloopsfor-loopordinal

解决方案


请注意,11、12 和 13 有th后缀。
另请注意,您可以更改函数中的行尾print(默认\n):

print('text', end=' ')
print('another text')

然后,我建议您使用格式化字符串使用f"{data} constant text"or "{} constant text".format(data)

这是我对您的问题的解决方案:

def getSuffix(n):
    if n < 0: raise Exception("Ordinal negative numbers are not allowed")
    if n % 100 in [11, 12, 13]: return 'th'
    if n % 10 == 1: return 'st'
    if n % 10 == 2: return 'nd'
    if n % 10 == 3: return 'rd'
    return 'th'


for number in range(1, 114):
    print(f"{number} is the {number}{getSuffix(number)} number")

我希望我是有帮助的。


推荐阅读