Home › Forums › Python Programming › repr() , str() , eval() in python
- This topic has 1 reply, 2 voices, and was last updated 11 years, 11 months ago by
Humble.
Viewing 2 posts - 1 through 2 (of 2 total)
-
AuthorPosts
-
admin
Guestrepr() stands for representation and its a “formal” representation ..where str() stands for “informal” way..
Ref# http://docs.python.org/2/reference/datamodel.html
object.__repr__(self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. object.__str__(self) Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object. In short what "repr()" give us is the same way python think or represent that object .. for str() I would say more human readable form.. For ex:>>> import datetime >>> datetime.datetime.now() datetime.datetime(2014, 1, 9, 20, 42, 13, 58580) >>> repr(datetime.datetime.now()) 'datetime.datetime(2014, 1, 9, 20, 42, 21, 598036)' >>> str(datetime.datetime.now()) '2014-01-09 20:42:32.587526' >>> 'eval(source[, globals[, locals]]) It evaluate the source in the context of globals and locals. The source may be a string representing a Python expression nor a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals.If only globals is given, locals defaults to it.' If you input repr() output as a source for "eval()" , you get the object back..
>>> x = repr(datetime.datetime.now()) >>> x 'datetime.datetime(2014, 1, 9, 20, 49, 45, 157694)' >>> eval(x) datetime.datetime(2014, 1, 9, 20, 49, 45, 157694) >>>
Humble
Keymasterrepr() function can be used to convert an integer to a string..
>>> type(100) <type 'int'> >>> type(repr(100)) <type 'str'> >>> repr(100) '100' >>>
-
AuthorPosts
Viewing 2 posts - 1 through 2 (of 2 total)