python - 使用循环动态查找序数: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.")
解决方案
请注意,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")
我希望我是有帮助的。
推荐阅读
- python - Flask 刷新时页面内容加倍
- powershell - Powershell v5.1 Invoke-RestMethod 错误解析正文
- altair - Vega-lite:将工具提示悬停在固定位置
- mesibo - Mesibo 本地集成问题
- amazon-web-services - 当我尝试从 Ubuntu 服务器而不是本地计算机推送到 S3 时,AWS 拒绝了我的凭据
- sqlite - 如何在 SQLite3 中按字母顺序显示元素
- kustomize - Kustomize:在版本“kustomize.config.k8s.io/v1beta1”中没有匹配类型“Kustomization”
- reactjs - 如何在反应打字稿中更改状态
- r - serve_site 加载核心 R 库, build_site 不在 blogdown 中
- batch-file - 在批处理中对字符串使用 %~n 两次