2013-03-02 155 views
0

嗯,我只是總是在python上使用%r,但我不知道何時必須使用這些其他格式...python中的%r,%s和%d有什麼區別?

+1

http://docs.python.org/2/library/string.html#format-examples – Daniel 2013-03-02 03:27:38

+0

在互聯網上確實存在某處 – thescientist 2013-03-02 03:28:09

+0

http://stackoverflow.com/questions/8986179/python-the-hard-way-exercise-6-r-versus-s – grc 2013-03-02 03:35:32

回答

14

這在the Python documentation中有解釋。總之,

  • %d將格式化一個數字顯示。
  • %s將插入對象的展現字符串表示(即str(o)
  • %r將插入對象(即repr(o)

如果格式化一個整數的規範化字符串表示,那麼這些都是當量。對於大多數物體而言,情況並非如此。

9

這裏是補充詹姆斯亨斯特萊吉的回答一個例子:

class Cheese(float): 
    def __str__(self): 
     return 'Muenster' 
    def __repr__(self): 
     return 'Stilton' 

chunk = Cheese(-123.4) 

print(str(chunk)) 
# Muenster 
print(repr(chunk)) 
# Stilton 
print(int(chunk)) 
# -123 
print('%s\t%r\t%d'%(chunk, chunk, chunk)) 
# Muenster Stilton -123 
相關問題