Python standard library: built-in Function format (value [, format_spec])

Source: Internet
Author: User

Python standard library: built-in Function format (value [, format_spec])

This function formats the value in the format of format_spec. However, the function explains that format_spec is determined by the value type. Different types have different formatting interpretations. When the format_spec parameter is null, this function is equivalent to the str (value) function.

In fact, this function is called to convert format (value, format_spec) to type (value ). the _ format _ (format_spec) method is called. Therefore, the _ format _ () method is searched for in the value type. If this method is not found, an exception TypeError is returned.

The format_spec format is as follows:

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

Fill: =

Align: = <| >|=| ^

Sign: = + |-|

Width: = integer

Precision: = integer

Type: = B | c | d | e | E | f | F | g | G | n | o | s | x | X | %

Fill indicates that any character can be entered.

Align is the Alignment Method, <is the left alignment,> is the right alignment, and ^ is the center alignment.

Sign is a symbol, + indicates a positive number, and-indicates a negative number.

Width indicates the total number of output digits.

Precision is the number of decimal reserved digits.

Type indicates the expression of the output numeric value. For example, B Indicates binary, E indicates exponential, and X indicates hexadecimal.

Example:

 

#format()print(format(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 output is as follows:

2918

500

0000003.14

03.14

3.141590E + 00

Test

Test

Test

 


 

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.