计数器有漂亮的python字符串格式吗? [英] Any pretty python string formatting for a counter?

查看:83
本文介绍了计数器有漂亮的python字符串格式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

预期输出:

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!

推荐答案

简单地说:

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.

这篇关于计数器有漂亮的python字符串格式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆