Home > Article > Backend Development > Python built-in functions - repr & str
Python built-in function - repr & str
repr & str
repr(object) & str(object)
The variable value is converted into a string Two mechanisms: the former's goal is accuracy, the latter's goal is readability
repr(object) returns a printable string representing the object.
This is consistent with the result obtained by conversion (backtick ``) processing.
As a normal function, you can use this operation, which is sometimes useful.
For most types, this function attempts to return a string. When passed to eval(), the same object will be generated,
(i.e. eval(repr(object)==object.) otherwise it will generate a A string enclosed in angle brackets,
contains the object type name and usually some additional information such as object name and object address.
A class can control its own instance by redefining the __repr__() member function regarding this function. Return value.
str(object) returns a printable friendly string representing the object.
For a string, the difference between
and repr(object) is that str(object) ) does not attempt to return a string passed to eval();
The goal is to return a printable string.
If no parameters are given, an empty string is returned (the same applies to classes, through _. The _str__() member controls its behavior)>>> print repr("hello world!")
'hello world!'
>>> print repr(10000L)
10000L
>>> print str("hello world!")
hello world!
>>> print str(10000L)
10000
>>> temp = 42
>>> print "the temperature is "+temp
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
print "the temperature is "+temp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "the temperature is "+ `temp`
the temperature is 42
>>> print "the temperature is " + repr(temp)
the temperature is 42
The above is the content of Python’s built-in function-repr & str. For more related content, please pay attention to the PHP Chinese website (www.php.cn)