Python formatted string with format

Source: Internet
Author: User

Format is a new way to format a string, and it has many advantages over the older version of the python2.6 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

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 of the Format_spec

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

Print 'Hello {0} I am {1}'. Format ('Kevin','Tom')#Hello Kevin I am TomPrint 'Hello {} I am {}'. Format ('Kevin','Tom')#Hello Kevin I am TomPrint 'Hello {0} I am {1}. My name is {0}'. Format ('Kevin','Tom')#Hello Kevin I am Tom my name is Kevin

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

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

3. Fill by subscript

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

names={'name':'Kevin','name2' :'Tom'}print'hello {names[name]}  I am { Names[name2]}'. Format (names=names)                  #  Hello Kevin i am Tom

Note Access to the dictionary key without the quotation marks

5. Through the properties of the object

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

6. Use magic Parameters

args=[' Lu ']
Kwargs = {'name1'Kevin'name2' ' 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

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

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

2.format as a function

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

3. Formatting datetime

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

4.{} embedded {}

Print '  '. Format ('Kevin', 50)  

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.

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

Python formats the string with format

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.