Usage of format in Python

Source: Internet
Author: User

Grammar

It replaces% with {} and:.
Map sample

By location

The Format function of the string can accept an unlimited number of parameters, the position can be out of order, can not be used or multiple times, but 2.6 can not be empty {},2.7.
by keyword

Through object properties

by subscript

With these convenient "mapping" methods, we have a lazy weapon. Basic Python knowledge tells us that list and tuple can be "broken" into normal parameters to the function, and dict can be broken into the keyword parameters to the function (through and *). So you can easily pass a list/tuple/dict to the Format function. Very flexible.
Format qualifier

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

Fill and align
Padding is used in conjunction with alignment
^, <, > center, Align Left, right, back with width
: The fill character after the number, only one character, not specified by default is filled with a space
Like what

Accuracy and type F
Accuracy is often used in conjunction with Type F

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

Other types

Mainly in the system, B, D, O, X are binary, decimal, octal, hexadecimal.

Use, the number can also be used to make the amount of thousands separator.

Format is a new way to format a string in python2.6, which has many advantages over the old version of the% format method.

1. There is no need to ignore the data type problem, in the% method%s can only replace the string type

2. Single parameter can be output multiple times, parameter order can be different

3. The filling method is very flexible and the alignment is very powerful.

4. The official recommended way, the% way will be eliminated in the later version

An example of format

1 Print ' Hello {0} '. Format(' World ')

Will output Hello World

Format formats

Replacement_field:: = "{" [Field_name] ["!" conversion] [":" Format_spec] "}" Field_name:: = Arg_nam E ("." Attribute_name | "[" Element_index "]") *arg_name:: = [Identifier | Integer]attribute_name:: = Identifierelement_index:: = Integer | Index_stringindex_string:: = <any source character except "]" > +conversion:: = "R" | "S" | "A" Format_spec:: = <described in the next section>format_spec format

Format_spec:: = [[Fill]align][sign][#][0][width][,][.precision][type]fill:: = <any Character>ali GN:: = "<" | ">" | "=" | "^" Sign:: = "+" | "-" | "Width:: = integerprecision:: = Integertype:: =" B "|" C "| "D" | "E" | "E" | "F" | "F" | "G" | "G" | "N" | "O" | "S" | "X" | "X" | “%”

Application:

A fill

1. Populating a string with a location

123 print ' Hello {0} I am {1} ' format ( ' Kevin ' ,< Span class= "crayon-s" > ' Tom ' )                    # Hello Kevin I am Tom print ' Hello {} I am {} ' format ( ' Kevin ' ,< Span class= "crayon-s" > ' Tom ' )                      # Hello Kevin I am Tom print ' Hello {0} I am {1}. My name is {0} '. Format(' Kevin ',' Tom ') # Hello Kevin I am Tom. My name is Kevin /c6>

Foramt will populate the arguments in the order of position, the first parameter is 0, then 1 ...

You can also fill in the order by not entering a number.

The same parameter can be populated multiple times, this is the format ratio of the advanced place

2. Fill with key

1 Print ' Hello {name1} I am {name2} '. Format(name1=' Kevin ',name2=' Tom ') # Hello Kevin I am T Om

3. Fill by subscript

123 names=[' Kevin ',' Tom '] print ' Hello {names[0]} I am {names[1]} '. Format(names=names) # Hello Kevin i am Tom print ' Hello {0[0]} I am {0[1]} '. Format(names) # Hello Kevin i am Tom

4. Through the dictionary key

12 names={ ' name ' : ' Kevin ' , ' name2 ' : ' Tom ' } print ' Hello {names[name]}  i am {names[name2]} ' .

Note Access to the dictionary key without the quotation marks

5. Through the properties of the object

12345 class Names(): name1=' Kevin ' name2=' Tom ' print ' Hello {names.name1} I am {names.name2} '. Format(names=names) # Hello Kevin i am Tom /c5>

6. Use magic Parameters

123 args=[' Lu '] kwargs = { ' name1 ' : ' Kevin ' , ' name2 ' :< Span class= "crayon-h" > ' Tom ' } print ' Hello {name1} {} I am {name2} '. Format(*args, **Kwargs) # Hello Kevin i am Tom

Two-format conversion

B, D, O, and X are binary, decimal, octal, hexadecimal, respectively.

Digital Format Output Describe
3.1415926 {:. 2f} 3.14 Keep two digits after the decimal point
3.1415926 {: +.2f} 3.14 Signed reserved two decimal places
-1 {: +.2f} -1 Signed reserved two decimal places
2.71828 {:. 0f} 3 With no decimals
1000000 {:,} 1,000,000 Comma-delimited number format
0.25 {:. 2%} 25% Percent format
1000000000 {:. 2e} 1.00E+09 Exponential notation
25 {0:B} 11001 Convert to Binary
25 {0:D} 25 Convert into decimal
25 {0:o} 31 Convert to Octal
25 {0:X} 19 Convert to hexadecimal

Three alignment and padding

Digital Format Output Describe
5 {: 0>2} 05 Number 0 (padding to the left, width 2)
5 {: X<4} 5xxx Number complement X (padding to the right, Width 4)
10 {: X^4} x10x Number complement X (padding to the right, Width 4)
13 {: 10} 13 Align Right (default, Width is 10)
13 {: <10} 13 Left-justified (width is 10)
13 {: ^10} 13 Middle Alignment (width 10)

Four other

1. Escaping the {and} symbols

1 Print ' {{0}}} '. Format(' Kevin ')

As% percent escaped%, Formate is escaped with two curly braces

2.format as a function

12 f = ' Hello {0} I am {1} '. Format print f(' Kevin ',' Tom ')

3. Formatting datetime

12 now=datetime. Now()print ' {:%y-%m-%d%x} '. Format(now)

4.{} embedded {}

1 Print ' Hello {0:>{1}} '. Format(' Kevin ',

5. Use of exclamation marks

! The following can be added S r a respectively corresponding to STR () repr () ASCII ()

The function is to use the corresponding function to process the parameters before filling.

12 print "{!s}". Format(' 2 ') # 2print "{!r} ". format(' 2 ') # ' 2 '

The difference is repr with quotation marks, str () is user-oriented, the purpose is readability, repr () is for the Python parser, and the return value represents the meaning within Python

ASCII () has been an error, maybe this is a 3.0 function

Reference: Https://docs.python.org/3/library/string.html#grammar-token-conversion

Usage of format in Python

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.