2012-02-20 21 views
3

是否有任何字符串格式化使用正確的後綴與日誌消息,例如:任何漂亮的Python字符串格式爲計數器?

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 

我會推出自己很容易,但我想知道是否有已經是一個內置的解決方案。如果沒有,我會接受最優雅的解決方案!

+3

見[這個問題](http://stackoverflow.com/questions/739241/python-date-ordinal-output)。 – DSM 2012-02-20 01:19:47

回答

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

或者如果你喜歡醜陋的黑客:

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

我覺得有點髒而寫的那一個。

+0

引人入勝的是,當你用這種方式寫出來的時候,你可以看到「[N百和]十一」 - 「二十」的發音如何不受特殊語言規則的影響,而「二十一」/二十一不是「二十-oneth「/ 21。真可怕。我一直沒有意識到規則是如此奇特,直到我看到這一點。 – ninjagecko 2012-02-20 02:13:09

+0

好吧,它的作品 - 不知道它是非常優雅的。可以通過擴展str.format來完成,這樣就可以像在我的例子中一樣使用接口了嗎? – wim 2012-02-20 02:28:44

+0

@wim:好吧,你總是可以修改它;)我不相信存在添加格式化程序的接口,所以它會變得很難看。 – 2012-02-20 12:44:27

0
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])] 

不是非常有效的,但絕對一個班輪)

+4

其實這很醜陋...現在我看着它。 – 2012-02-20 04:27:16

+0

and b0rked for 11,12,13 – wim 2012-02-20 04:31:48

+0

啊,是的。現在修復。而且,即使更醜陋 – 2012-02-20 04:37:55