是否有任何字符串格式可以在日志消息中使用正确的后缀,例如:
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/