Python formatted string Format function

Source: Internet
Author: User

Read Mattkang's notes in CSDN's blog, "The flowing Python-enhanced formatted string format function"

Since python2.6, a new function Str.format () has been added to the format string, which replaces% with {} and:.

1. Map instances

IN[1]:'{0},{1}'. Format ('ABC', 18) out[1]:'abc,18'in[2]:'{}'. Format (18) out[2]: 18in[3]:'{1},{0},{1}'. Format ('ABC', 123) out[3]:'123,abc,123'in[4]:'{Name}, {age}'. Format (age=18, name ='ABC') out[4]:'ABC,'in[5]: p = ['ABC', 18]in[6]:'{0[0]}, {0[1]}'. Format (p) out[6]:'ABC,'

2. Format qualifier

It has a rich format qualifier (syntax is in {} with:), such as:

Fill and align:

Fill want to use it together

^, <, > is centered, left-aligned, right-aligned, followed by width

: The character after the fill, can only be one character, not specified by default with a space padding

Like what:

' {: >8} '. Format ('189') out['     189'in ['{: 0>8}'. Format ('189') out[  '00000189'

Accuracy and type

Accuracy is often used in conjunction with Type F

' {:. 2f} '. Format (321.3456) out['321.34'

Where. 2 represents a precision of 2 length, and F represents a float type.

Other types

Mainly binary, B, D, O, x binary, Decimal, octal, and hexadecimal, respectively

 in[10]:  {:b}   ' . Format (17) out[]:  " 10001    in[ all]:  '    

To use, the number can also be used to make the amount of thousands separator

' {:,} '. Format (1234567890) out['1,234,567,890'

Python formatted string Format function

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.