"Python" python input and output

Source: Internet
Author: User
Tags lua value of pi pprint

Output format beautification

Python two output is worth the way: the expression statement and the print () function (the third Way is to use the write () method of the file object standard output file can be referenced by sys.stdout)

If you want the output pair to be more versatile, you can use the Str.format () function to format the output value

If you want to convert the output value to a string, you can do so using the repr () or str () function.
The STR () function returns a user-readable representation.
Repr () produces an interpreter-readable representation.

Such as

s =' Hello,world. 'STR (s) >>>' Hello,world. 'Repr (s) >>>"' Hello,world. '"Str1/7) >>>' 0.14285714285714285 'x =Ten*3.25y = $* $s =' The value of x is '+ repr (x) +', and y is '+ repr (y) +' ... 'Print(s) The value ofX is 32.5, andY is 40000... Hello =' hello,world\n 'hellos = repr (hello)Print(hellos) >>>' Hello,world '

Output square cubic meter

The #rjust () method can put a string to the right and fill a space on the left.  forI in range (1, One):Print(Repr (x). Rjust (2), repr (x*x), Rjust (3), end="')Print(Repr (x*x*x). Rjust (4)) >>>1   1    1 2   4    8 3   9    - 4   -    - 5   -   the 6   $  216 7   the  343 8   -   + 9  Bayi  729Ten  -  + for xIn range (1, One):Print(' {0:2d} {1:3d} {2:4d} '.format(x,x*x,x*x*x)) >>>1   1    1 2   4    8 3   9    - 4   -    - 5   -   the 6   $  216 7   the  343 8   -   + 9  Bayi  729Ten  -  +

Str.format () Usage:
{} and the characters inside are replaced by the parameters in format (). The number in parentheses is used to point to the position of the incoming object in format ()
Such as

>>> print(‘{0} and {1}‘.format(‘spam‘‘eggs‘and eggs>>> print(‘{1} and {0}‘.format(‘spam‘‘eggs‘and spam

If the keyword function is used in format (), then their values will point to the parameter that uses that name

>>> print(‘This {food} is {adjective}.‘.format(...       food=‘spam‘, adjective=‘absolutely horrible‘))This spam is absolutely horrible.

The position and keyword parameters can be arbitrarily combined

>> print(‘The story of {0}, {1}, and {other}.‘.format(‘Bill‘‘Manfred‘,                                                       other=‘Georg‘ofand Georg.

'!a ' (using ASCII ()), '!s ' (using str ()) and '!r ' (using repr ()) can be used to convert a value before it is formatted:

>>> import math>>> print(‘The value of PI is approximately {}.‘.format(math.pivalueofPI3.14159265359.>>> print(‘The value of PI is approximately {!r}.‘.format(math.pivalueofPI3.141592653589793.

The optional ":" and format identifiers can be followed by the field name. This allows for better formatting of values. The following example holds the PI to three digits after the decimal point:

mathprint(‘{0:3f}‘.format(math.pi))>>>3.142

Passing in an integer after ': ' Guarantees that the field has at least so many widths and is useful for beautifying tables.

If you have a long format string and you don't want to separate it, it would be nice to pass the variable name instead of the location when you format it.

The simplest is to pass in a dictionary and then use square brackets ' [] ' to access the key value:

table = {‘Sjoerd‘4127‘Jack‘4098‘Dcab‘8637678print(‘Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ‘          ‘Dcab: {0[Dcab]:d}‘.format(table409841278637678

You can also achieve the same functionality by using ' * * ' before the table variable:

table = {‘Sjoerd‘4127‘Jack‘4098‘Dcab‘8637678print(‘Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}‘.format(**table409841278637678
Legacy string Formatting
>>> import math>>> print(‘The value of PI is approximately %5.3f.‘is3.142.
Read and write files

Open () Returns a file object with the following basic syntax format
Open (Filename,mode)
Such as

f = open ('/tmp/workfile ', ' W ')
The first parameter causes the file name to be opened
The second parameter describes how the file uses the characters. Mode can make ' R ' if the file is read-only. The ' W ' is used only for writing (if a file with the same name is present, it will be deleted). ' A ' is used to append file contents. Any data written will be automatically added to the end. ' r+ ' is also used for both reading and writing.
The mode parameter is optional and ' R ' is the default value

Method of the File Object F.read ()

In order to read the contents of a file, call F.read (size).
A certain number of data is read and then returned as a string or a byte object.
Size is an optional parameter of the numeric type. when size is ignored or negative, all the contents of the file are read and returned.

f.readisthefile.\n‘
F.readline ()

Reads a single line. If an empty string is returned, the last line is read

isthefirstofthefileofthefile\n‘>>> f.readline()‘‘
F.readlines ()

Returns all the rows in the file

isthefirstofthefileofthefile\n‘]

Another way is to iterate over a file object and then read each line:

forin f:...     print(line, end=‘‘)...This is the first line of the file.Second line of the file

This method is simple, but does not provide a good control. Because the processing mechanism of the two is different, it is best not to mix.

F.write ()

F.write (String) writes a string to the file, and then returns the number of characters written

f.write(‘This is a test\n‘)>>>15

If you are not writing a string, you need to first convert

>>> value = (‘the answer‘42)>>> s = str(value)>>> f.write(s)18
F.close ()

After processing a file, call F.close () to close the file and release the system's resources, and throw an exception if you try to call the file again
You can also use the WITH statement. The end will help you close the file correctly, writing it is also shorter than the try finally

withopen(‘/tmp/workfile‘,‘r‘as f:    read_data = f.read()f.closed>>>True
Pickle Module

Python's pickle module implements basic data sequence and deserialization.
Through the serialization of the Pickle module we are able to save the object information that is running in the program to the file and store it permanently.
The deserialization operation of the Pickle module allows us to create an object from a file that was last saved by the program.

Basic interface:

pickle.dump(obj,file,[,protocol])

With the Pickle object, you can open the file as read:

x = pickle.load(file)#从file中读取一个字符串,并将它重构为原来的python对象

File: Class files object with Read () and ReadLine () interfaces

Example 1:

#使用pickle模块将数据对象保存到文件import pickledata1 = {‘a‘:[1,2.0,3,4+6j],         ‘b‘:(‘string‘,u‘Unicode string‘)         ‘c‘:None}selfref_list = [1,2,3]selfref_list.append(selfref_list)output = open(‘data.pk1‘,‘wb‘)pickle.dump(data1,output)pickle.dump(selfref_list,output,-1)output.close()

Example 2:

open(‘data.pk1‘,‘rb‘)data1 = pickle.load(pk1_file)pprint.pprint(data1)data2 = pickle.load(pk1_file)pprint.pprint(data2)pkl_file.close()

"Python" python input and output

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.