Python3.2 official document tutorial --- formatting output

Source: Internet
Author: User

There are many ways to output a program. data can be printed or written to a file in the form that people can understand for future use. This chapter discusses these issues.

5.1 format the output

Currently, we have come into use two output value methods: expression statements and print () functions. (The third method is to use the write () method in the file object. For standard file output, refer to the sys. stdout library file)

You often want to control the output formatted data rather than simply using spaces to separate characters. There are two ways to format your output data. The first method is to process all the strings by yourself. You can use the splitting or link operations in the strings to create any characters you want. The standard module string contains some useful operations to populate the string with the specified column width, which will be discussed later. The second method is to use str. format.

The String module contains a template class, which provides another method to convert values into strings. Of course, there is a problem: how do you convert a value to a string? Fortunately, python has provided various methods for converting any value into a string: Pass the value to the method repr () or str ();

The Str () function is used to return a form that is more readable. The repr () method is used to generate a convenient form of interpreter. (If there are no equal statements, syntaxerror is generated ). The return value of str () is the same as that of repr. These two methods can be used to generate the same representation for more values, such as numbers or structures similar to lists and dictionaries. Specifically, strings have two different performance implementations.

For example:

>>> S = 'hello, world .'

>>> Str (s)

'Hello, world .'

>>> Repr (s)

"'Hello, world .'"

>>> Str (1/7)

'0. 100'

>>> X = 10*3.25

>>> Y = 200*200

>>> S = 'the value of x is '+ repr (x) +', and y is '+ repr (y) + '...'

>>> Print (s)

The value of x is 32.5, and y is 40000...

>>># The repr () of a string adds string quotes and backslashes:

... Hello = 'hello, world \ N'

>>> Hellos = repr (hello)

>>> Print (hellos)

'Hello, world \ N'

>>># The argument to repr () may be any Python object:

... Repr (x, y, ('spam', 'egg ')))

"(32.5, 40000, ('spam', 'egg '))"

There are two ways to output a table with squares:
>>> For x in range (1, 11 ):

... Print (repr (x). Reset ust (2), repr (x * x). Reset ust (3), end = '')

... # Note use of 'end' on previous line

... Print (repr (x * x). Limit ust (4 ))

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

>>> For x in range (1, 11 ):

... Print ('{0: 2d} {1: 3d} {2: 4d}'. format (x, x * x, x * x ))

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

(Note that in the first example, use the print () method to add spaces to each column: it can also add spaces between parameters)

The method in the example describes the application of str. Must ust () in the string class. It is right aligned by filling spaces of the specified width on the left side of the string. There are two similar methods: str. ljust () and str. center (). These methods are not used to write any data and they return a new string. If the input string is too long, it will not be truncated, but will be returned as is. This may be a mess in your list, but it is better than truncation, so the wrong value will be output (if you want to truncation, you can always use the slicing operation, such as x. ljust (n) [: n])

Another method is zfile (), which uses zero to fill the left side of the numeric string (to the specified width ). It can understand positive and negative numbers.

>>> '12'. zfill (5)

'123'

>>> '-3.14'. zfill (7)

'-003.14'

>>> '3. 14159265359 '. zfill (5)

'3. 100'

The basic usage of the Str. format () method is as follows:

>>> Print ('We are the {} who say "{}! "'. Format ('knights', 'ni '))

We are the knights who say "Ni! "

Parentheses and the characters contained (called the format field) will be replaced by the object passed in str. format. Data in brackets

Refers to the location of the object passed to the formatting method.

>>> Print ('{0} and {1}'. format ('spam', 'eggs '))

Spam and eggs

>>> Print ('{1} and {0}'. format ('spam', 'eggs '))

Eggs and spam

If the keyword parameters are used in the str. format () method, their values are specified by the parameter name.

>>> Print ('this {food} is {adjective}. '. format (

... Food = 'spam', adjective = 'absolutely horrible '))

This spam is absolutely horrible.

Location and keyword parameters can be used in combination at will.

>>> Print ('The story of {0}, {1}, and {other}. '. format ('bill', 'manfred ',

Other = 'georg '))

The story of Bill, Manfred, and Georg.

'! A' (apply ascii ()),'! S '(apply str () and '! R' (apply repr () can be used to convert values before formatting.
>>> Import math

>>> Print ('the value of PI is approximately {}. '. format (math. pi ))

The value of PI is approximately 3.14159265359.

>>> Print ('the value of PI is approximately {! R}. '. format (math. pi ))

The value of PI is approximately 3.141592653589793.

The character name can be followed by an optional ":" symbol and a formatting classifier. This is how to better control the formatting method. The following example splits the PI decimal point into three digits.

>>> Import math

>>> Print ('the value of PI is approximately {0:. 3f}. '. format (math. pi ))

The value of PI is approximately 3.142.

After ":", passing an integer will set the minimum number of characters in the character width. This is useful for Beautifying tables.

>>> Table = {'sjoerd': 4127, 'jack': 4098, 'dcab ': 7678}

>>> For name, phone in table. items ():

... Print ('{0: 10 }=> {1: 10d}'. format (name, phone ))

...

Jack => 4098

Dcab ==> 7678

Sjoerd => 4127

If you have a long formatted character, but you do not want to separate it, it is better to use a name instead of a location to reference the variable to be converted into different types. This can be simply by passing a dictionary, and use square brackets '[]' to access all primary keys.

>>> Table = {'sjoerd': 4127, 'jack': 4098, 'dcab ': 8637678}

>>> Print ('Jack: {0 [Jack]: d}; Sjoerd: {0 [Sjoerd]: d };'

'Dcab: {0 [Dcab]: d} '. format (table ))

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This function is implemented by using the "**" table as the keyword parameter. For example

>>> Table = {'sjoerd': 4127, 'jack': 4098, 'dcab ': 8637678}

>>> Print ('Jack: {Jack: d}; Sjoerd: {Sjoerd: d}; Dcab: {Dcab: d} '. format (

**

Table ))

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is particularly useful when combined with the new built-in function vars (). It returns a dictionary containing all local variables, the string formatting method str. for details about format (), see Format String Syntax.

5.1.1 format legacy strings

The % operator can also be used to format a string. It interprets the left parameter like the: cfunc: 'sprintf-'Format String style and acts on the right parameter, and returns the string result from the formatting operation, for example:

>>> Import math

>>> Print ('the value of PI is approximately % 5.3f. '% math. pi)

The value of PI is approximately 3.142.

Because str. format () is a new method, many python code still uses the % operator. However, the old formatting style will eventually be removed from the language. Str. format is widely used.

For more information, see the format of the old string.

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.