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

wim*_*wim 3 python printing logging string-formatting

是否有任何字符串格式用于使用正确的后缀和日志消息,例如:

for n in itertools.count():
  print 'printing for the {:nth} time'.format(n)
Run Code Online (Sandbox Code Playgroud)

预期产量:

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
Run Code Online (Sandbox Code Playgroud)

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

Nik*_* B. 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')
Run Code Online (Sandbox Code Playgroud)

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

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

写这篇文章的时候我觉得有点脏.