Any pretty python string formatting for a counter?

喜夏-厌秋 提交于 2019-12-04 12:41:06

What about simply:

def stringify(x):
  if x // 10 % 10 == 1:
    return str(x) + 'th'
  else:
    return str(x) + { 1:'st', 2:'nd', 3:'rd' }.get(x % 10, 'th')

Or if you prefer ugly hacks:

return str(x) + { 1:'st', 2:'nd', 3:'rd' }.get(x//10%10 != 1 and x%10, 'th')

I felt a bit dirty while writing that one.

ordinal = lambda x: str(x) + ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'][0 if int(str(x)[-2:]) > 9 and int(str(x)[-2:]) < 21 else int(str(x)[-1])]

Not extremely efficient, but definitely a one-liner ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!