Python standard library: Built-in function format (value[, Format_spec])

Source: Internet
Author: User

This function formats values in format_spec format, whereas function interpretation format_spec is based on the type of value to determine, different types have different formatting interpretations. When the parameter format_spec is empty, this function is equivalent to the way the function str (value) is .

In fact, when this function is called, the format (value, Format_spec) is converted to type (value). __format__ (format_spec) method __format__ ()is found in the value type, andif this method is not found, an exception is returned TypeError .

where format_spec is written in the following form:

Format_spec:: = [[Fill]align][sign][#][0][width][,][.precision][type]

Fill:: = <any character>

Align:: = "<" | ">" | "=" | "^"

Sign:: = "+" | "-" | " "

Width:: = integer

Precision:: = integer

Type:: = "B" | "C" | "D" | "E" | "E" | "F" | "F" | "G" | "G" | "N" | "O" | "S" | "X" | "X" | "%"

Fill means that any character can be filled in.

Align is alignment,< is left- aligned, > is Right-aligned,^ is center-aligned.

sign is a symbol, + denotes a plus sign, - denotes a minus.

Width is the number of digits, indicating how many digits are output in total.

Precision is the number of decimal reserved digits.

Type is the representation of the output numeric value, for example, b is a binary representation, for example , E is an exponential representation, for example , X is a hexadecimal representation.

Example:

#format () print (2918) print (Format (0x500, ' X ')) print (Format (3.14, ' 0=10 ')) print (Format (3.14159, ' 05.3 ')) Print (Format (3.14159, ' E ')) Print (Format (' Test ', ' <20 ') print (Format (' Test ', ' >20 ')) Print (Format (' Test ', ' ^20 ‘))

The resulting output is as follows:

2918

500

0000003.14

03.14

3.141590E+00

Test

Test

Test


Cai Junsheng qq:9073204 Shenzhen

Python standard library: Built-in function format (value[, Format_spec])

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.