Python built-in functions str () and repr ()

Source: Internet
Author: User

Python built-in functions str () and repr ()

Built-in functions: str (), repr () (representation, expression, expression), or quotation mark operator ('') you can easily obtain the object content, type, numeric attributes, and other information in string mode.

The str () function makes the string readable (so it is called by print)

The string obtained by the repr () function can be used to obtain the object again. In general, the equation obj = eval (repr (obj) is true. These two functions take an object as its parameter and return an appropriate string.

In fact, repr () and ''do the same thing and return the" official "string of an object. In most cases (not all), the object can be re-obtained through the evaluate operation (built-in function eval.

Str () is different. It generates a readable string representation of an object. The result is usually not evaluated using eval (), but is suitable for print output.

For example:

>>> Class D (object ):... def _ str _ (self ):... return "a _ str __"... def _ repr _ (self ):... return "a _ repr _"...> dr = D () >>> print dra _ str __>>>> dra _ repr __>>>> "% s" % dr 'A _ str _ '>>>> "% r" % dr 'A _ repr __'

Why do you still need ''with repr ''?

In Python, some operators and functions do the same thing, because in some cases, functions are more suitable for use than operators. For example, function objects can be passed as parameters. The Double Star (**) multiplication method and the pow () built-in function both return the Power y of x.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.