Any pretty python string formatting for a counter?

2019-04-12 10:42发布

Is there any string formatting for using correct suffix with log messages, for example:

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

Expected output:

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

I could roll my own fairly easily, but I was wondering if there was already a built-in solution. If not, I will accept as answer the most elegant solution!

2条回答
爷、活的狠高调
2楼-- · 2019-04-12 11:29
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 ;)

查看更多
SAY GOODBYE
3楼-- · 2019-04-12 11:31

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.

查看更多
登录 后发表回答