python - Quelle est la différence entre str et repr

Mots clés : pythonmagic-methodsreprpython

meilleur 4 Réponses python - Quelle est la différence entre str et repr

vote vote

95

return "%s(%r)" % (self.__class__, self.__dict__) 
log(INFO, "I am in the weird function and a is", a, "and b is", b, "but I got a null C — using default", default_c) 
[moshe is, 3, hello world, this is a list, oh I don't know, containing just 4 elements] 
print "[" + ", ".join(l) + "]" 
vote vote

90

>>> class Sic(object): pass ...  >>> print str(Sic()) <__main__.Sic object at 0x8b7d0> >>> print repr(Sic()) <__main__.Sic object at 0x8b7d0> >>>  
>>> class Sic(object):  ...   def __repr__(object): return 'foo' ...  >>> print str(Sic()) foo >>> print repr(Sic()) foo >>> class Sic(object): ...   def __str__(object): return 'foo' ...  >>> print str(Sic()) foo >>> print repr(Sic()) <__main__.Sic object at 0x2617f0> >>>  
vote vote

78

>>> s="""w'o"w""" >>> repr(s) '\'w\\\'o"w\'' >>> str(s) 'w\'o"w' >>> eval(str(s))==s Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<string>", line 1     w'o"w        ^ SyntaxError: EOL while scanning single-quoted string >>> eval(repr(s))==s True 
vote vote

62

>>> import datetime >>> today = datetime.datetime.now() >>> str(today) '2012-03-14 09:21:58.130922' >>> repr(today) 'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)' 

Questions similaires