计数器的任何漂亮的python字符串格式?

时间:2012-02-20 00:48:28

标签: python logging printing string-formatting

是否存在使用正确后缀和日志消息的字符串格式,例如:

for n in itertools.count():
  print 'printing for the {:nth} time'.format(n)

预期产出:

printing for the 0th time
printing for the 1st time
printing for the 2nd time
printing for the 3rd time
printing for the 4th time
printing for the 5th time
...
printing for the 23rd time
...
printing for the 42nd time
...
etc

我可以很容易地自己动手,但我想知道是否已有内置解决方案。如果没有,我会接受最优雅的解决方案作为答案!

2 个答案:

答案 0 :(得分:8)

简单地说:

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')

或者如果你喜欢丑陋的黑客:

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

写这篇文章时我觉得有点脏。

答案 1 :(得分:0)

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])]

不是非常有效,但绝对是单线;)