3.1.3 syntax for formatting strings and 3.1.3 string syntax

Source: Internet
Author: User

3.1.3 syntax for formatting strings and 3.1.3 string syntax

Both the str. format () and Formatter types use the same format string. The formatted characters use braces {} to include the replaced fields. Any characters not in the braces are directly output without conversion. Therefore, to output braces, you need to use a special method to output braces using double braces, for example, {to output }.

 

The syntax for formatting strings is as follows:

Replacement_field: = "{" [field_name] ["! "Conversion] [": "format_spec]"}"

Field_name: = arg_name ("." attribute_name | "[" element_index "]") *

Arg_name: = [identifier | integer]

Attribute_name: = identifier

Element_index: = integer | index_string

Index_string ::= <any source character t "]"> +

Conversion: = "r" | "s" | ""

Format_spec: = <described in the next section>

 

3.1.3.1 Format String description string

 

The syntax of the format string description string is as follows:

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" | "%"

 

3.1.3.2 example of formatting a string

The following example uses the new format instead of the old % format. However, in most cases, the new format syntax is similar to the old syntax. Use braces {} and semicolons: to replace percent sign %. For example, '% 03.2f' indicates '{: 03.2f }'. However, the new formatting method also has some new options and different usage methods, as shown in the following example:

 

Access parameters by location:

# String

 

Import string

 

Print ('{0}, {1}, {2}'. format ('A', 'B', 'C '))

Print ('{},{},{}'. format ('A', 'B', 'C '))

Print ('{2}, {1}, {0}'. format ('A', 'B', 'C '))

Print ('{2}, {1}, {0}'. format (* 'abc '))

Print ('{2}, {1}, {2}'. format ('abc', '123', '123 '))

 

The output is as follows:

A, B, c

A, B, c

C, B,

C, B,

888,123,888

In this example, the statements '{0}, {1}, {2 }'. in format ('A', 'B', 'C'), 0, 1, and 2 are the sequence numbers of the positional parameters. {0} indicates replacing the output with the parameter 'A, the serial number of the positional parameter starts from 0 and increases from left to right.

In the statement '{},{},{}'. in format ('A', 'B', 'C'), if no location parameter is specified, output is based on the default location. If the number of braces is less than the number of location parameters, then, the output is ignored for subsequent parameters. In the statement {2}, {1}, {0 }'. in format ('A', 'B', 'C'), we can see that the location parameter can be placed on different output locations. Therefore, its output is converted into a c letter first, the last is output. In the statement '{2}, {1}, {0 }'. in format (* 'abc'), the parameter list resolution mechanism is mainly used here. The asterisk * is added before the parameter 'abc', that is, the parameter is first converted into a list before processing, the position of each item in the list corresponds to the location parameter specified in the output, so the output of this statement is in the order of c, B, and. In the statement '{2}, {1}, {2 }'. in format ('abc', '123', '123'), the location parameters are repeated or missing.

 

Access parameters by name:

Print ('mouse :( {x}, {y}) '. format (x = '000000', y = '000000 '))

Mousept = {'X': '000000', 'y': '000000 '}

Print ('mouse :( {x}, {y}) '. format (** mousept ))

The output is as follows:

Mouse :( 100,200)

Mouse :( 200,888)

In the statement 'mouse :( {x}, {y })'. in format (x = '000000', y = '000000'), no number is found in the preceding position parameter. Instead, the parameter x and y are replaced. Of course, the format parameter must be passed in as a keyword parameter to match these keyword parameters with the specified output name. In the statement 'mouse :( {x}, {y })'. in format (** mousept), the dictionary parameter mousept is directly used for input, and then two asterisks are used to reverse parse the dictionary parameter into a keyword parameter.

 

Access parameter attributes:

Print ('real part = {0. real} virtual part = {0. imag} '. format (3 + 4j ))

Class Point:

Def _ init _ (self, x, y ):

Self. x, self. y = x, y

Def _ str _ (self ):

Return 'point ({self. x}, {self. y}) '. format (self = self)

Print (str (Point (5, 5 )))

The output result is as follows:

Attribute access with a plural number, real part = 3.0 virtual part = 4.0

Point (5, 5)

In the statement 'Plural attribute access, real part = {0. real} virtual part = {0. imag }'. in format (3 + 4j), the attribute of the complex number is directly accessed in formatting, and the result attribute can be directly output in the string. In the 'point ({self. x}, {self. y })'. in format (self = self), you can directly copy the attributes of the class and print out the values of the class attributes. This is much easier than re-writing the attributes in the Formatting Function, enter less characters.

 

Access parameters:

Xy = (20, 30)

Print ('x axis: {0 [0]}, Y axis: {0 [1]} '. format (xy ))

The output result is as follows:

X axis: 20, Y axis: 30

In this example, we can see that the items that directly access the tuples in formatting, for example, 0 [0] indicates accessing the first item of the first parameter, 0 [1] indicates the second entry of the first parameter.

 

Use! S and! R to replace % s and % r:

Print ('repr ():{! R}; str ():{! S} '. format ('abc', '123 '))

The output result is as follows:

Repr (): 'abc'; str (): 123

In this example, we can see the usage! S to replace % s, which is simpler and more convenient! Replace % r with r.

 

String arrangement and width alignment

Print ('{:< 30}'. format ('left alignment '))

Print ('{:> 30}'. format ('Right alignment '))

Print ('{: ^ 30}'. format ('center alignment '))

Print ('{: * ^ 30}'. format ('center alignment '))

The output result is as follows:

Left aligned

Right alignment

Center alignment

************* Center alignment *************

 

Replace % + f, %-f, and % f, and format the Floating Point Number of the specified symbol.

Print ('{: + f };{: + f}'. format (0.618,-0.618 ))

Print ('{: f };{: f}'. format (0.618,-0.618 ))

Print ('{: f };{: f}'. format (0.618,-0.618 ))

Print ('{:-f}; {:-f}'. format (0.618,-0.618 ))

The output result is as follows:

+ 0.618000;-0.618000

0.618000;-0.618000

0.618000;-0.618000

0.618000;-0.618000

 

Replace % x and % o, and format the same value as a different hexadecimal output.

Print ('int: {0: d}; hex: {0: x}; oct: {0: o}; bin: {0: B }'. format (55 ))

Print ('int: {0: d}; hex: {1: x}; oct: {0: o}; bin: {0: B }'. format (55, 64 ))

Print ('int: {0: # d}; hex: {0: # x}; oct: {0: # o}; bin: {0: # B }'. format (55 ))

The output result is as follows:

Int: 55; hex: 37; oct: 67; bin: 110111

Int: 55; hex: 40; oct: 67; bin: 110111

Int: 55; hex: 0x37; oct: 0o67; bin: 0b110111

 

Use commas as the delimiter for thousands of Characters

Print ('{:,}'. format (9876543210 ))

Print ('{0:,}'. format (88888888888889876543210 ))

The output result is as follows:

9,876,543,210

88,888,888,888,889,876,543,210

 

Output percentage value during formatting

Print ('percentage output: {:. 2%} '. format (50/100 ))

Print ('percentage output: {:. 2%} '. format (1.08 ))

The output result is as follows:

Percentage output: 50.00%

Percentage output: 108.00%

 

Output time format during formatting

Import datetime

D = datetime. datetime (2015, 1, 13, 12, 30, 59)

Print ('time formatting: {: % Y-% m-% d % H: % M: % S} '. format (d ))

The output result is as follows:

Time Format: 12:30:59

 

Nested formatting Parameters

For align, text in zip ('<^>', ['left', 'zhong', 'right']):

Print ('{0: {fill} {align} 16}'. format (text, fill = align, align = align ))

 

Width = 5

For num in range (5, 12 ):

For base in 'dxob ':

Print ('{0: {width} {base}'. format (num, base = base, width = width), end = '')

Print ()

The output result is as follows:

Left <

^

>>>>>>>>>>>>>> Right

 

5 5 5 101

6 6 6 110

7 7 111

8 8 10 1000

9 9 11 1001

10 A 12 1010

11 B 13 1011

Multiple formatting templates are tied together

IPAddr = [192,168, 0, 8]

Print ('{: 02X} {: 02X} {: 02X} {: 02X}'. format (* IPAddr ))

The output result is as follows:

C0A80008

 



Cai junsheng QQ: 9073204 Shenzhen

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.