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

标签 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

我可以相当轻松地推出自己的解决方案,但我想知道是否已经有内置解决方案。如果没有,我将接受最优雅的解决方案作为答案!

最佳答案

简单来说:

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

我写那个的时候觉得有点脏。

关于python - 任何用于计数器的漂亮 python 字符串格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354912/

相关文章:

debugging - 如何一致地组织代码以进行调试?

javascript - 简单打印示例

python - 如何使用 xlsxwriter for python 将数据导出到 xlsx

java - 无法关闭 HttpClient Wire 调试日志消息

python - 在 PyQt 上显示嵌入图像?

MongoDB:如何禁用记录警告:ClientCursor::staticYield 无法解锁递归锁的 b/c?

javascript - 在每个打印页面的顶部留出空间

c++ - C DLL 和 Python CTypes - 发布/调试中的不同返回

python - 将 matplotlib 图与 LaTeX 中的文本对齐

python - 提取一个 2 元素元组并将其转换为字符串