Analysis of input and output instances based on Python3 and analysis of python3 instances
Generally, a Python program can read input from the keyboard or from a file. The program results can be output to the screen or saved to a file for later use. This article introduces the most basic I/O functions in Python.
I. Console I/O
1. Read keyboard input
The built-in function input ([prompt]) is used to read a row from the standard input and return a string (remove the line break at the end ):
s = input("Enter your input:")
Note: The raw_input () function is canceled in Python 3.x.
2. Print to the screen
The simplest output method is to use the print statement. You can pass zero or multiple expressions separated by commas:
print([object, ...][, sep=' '][, end='endline_character_here'][, file=redirect_to_here])
Optional in square brackets. sep indicates the delimiter, end indicates the Terminator, and file indicates the redirected file. If you want to specify values for sep, end, and file, you must use the keyword parameter.
Print ('hello', 'World', sep = '%') # output hello % world print ('hello', 'World', end = '*') # output hello world * Without line feed
Ii. file I/O
Before reading and writing a file, use the open () function to open a file, which returns a file object ):
f = open(filename,mode)
If the mode parameter is not specified, the file is opened in 'R' mode by default. The characters in the mode include:
R: Read-Only
W: Write-only. If the file already exists, overwrite it. If the file does not exist, create a new file.
+: Read/write (cannot be used separately)
A: open the file for append. Only write. If the file does not exist, create a new file.
B: Open in binary mode (cannot be used separately)
Possible models include r, w, r +, w +, rb, wb, rb +, wb +, a, a +, AB, and AB +, note that only w and a can create files.
Usually, files are opened in text mode, that is, the read and write from the file is encoded in a specific encoding format (the default is the UTF-8). If the file is opened in binary mode, the data is read and written as a Byte object:
F = open('a.txt ', 'wb +') f. write ('I like apple! ') # Error f. write (B' I like apple! ') # Read and Write in bytes object form
A Bytes object is an unmodifiable integer sequence from 0 to 127, or a pure ASCII character. It is used to store binary data.
You can add 'B' to a string to create a bytes literal;
You can also use the bytes () function to create a bytes object.
Note: If the initialized bytes () function is a string, an encoding must be provided.
B1 = B 'this is string 'b2 = bytes ('this is string', 'utf-8') # The encoding format must be specified.
The string object is incompatible with the Byte object. To convert bytes to str, the bytes object must be decoded using the decode () method:
B = bytes ('this is string', 'utf-8') print (B, B. decode (), sep = '\ n') # output: # B 'this is string' # This is string
File object method (assuming f is a file object ):
F. read (size): reads data of size bytes and returns the data as a string or bytes object. Size is an optional parameter. If no size is specified, all content of the file is read.
F. readline (): Read a row. A linefeed (\ n) is left at the end of the string. If it is at the end of the file, an empty string is returned.
F. readlines (): reads all rows and stores them in the list. Each element is a row, which is equivalent to list (f ).
F. write (string): writes a string to a file, and returns the number of characters written. If you write files in binary mode, you need to convert string to bytes object.
F. tell (): returns the current location of the object, which is the number of bytes starting from the beginning of the object.
F. seek (offset, from_what): changes the position of the object. Offset is the offset relative to the reference position. from_what values: 0 (File Header, default), 1 (current position), and 2 (end of the file) indicate the reference position.
F. close (): close the object.
These are common methods. Of course, there are more than these methods for file objects. Depending on the open mode, the types of file objects returned by open () are also different:
TextIOWrapper: In text mode, the TextIOWrapper object is returned.
BufferedReader: Read Binary, that is, rb. The BufferedReader object is returned.
BufferedWriter: writes and appends binary data, that is, wb and AB. The BufferedWriter object is returned.
BufferedRandom: read/write mode, that is, the mode with + is returned.
You can run dir () or help () on these file objects to view all their methods.
Supplement:
1. In text mode, the seek () method locates only relative to the start position of the file. (Seek (0, 2) can be used to locate the end of a file)
2. You can iterate through a file object to read one row in a row:
for line in f: print(line, end='')
3. format the output
In general, we want to control more output formats, rather than simply separating them by spaces. There are two methods:
The first type is controlled by yourself. Use string slicing, join operations, and some useful operations contained in string.
The second method is to use str. format.
The following is an example:
# Method 1: self-control for x in range (1, 11): print (str (x ). must ust (2), str (x * x ). must ust (3), end = '') print (str (x * x ). must ust (4) # Method 2: str. format () for x in range (1, 11): print ('{0: 2d} {1: 3d} {2: 4d }'. format (x, x, x) # The output is: #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
In the first method, the str of the string object. the function of the just ust () method is to right the string and fill in spaces on the left by default. Similar methods include str. ljust () and str. center (). These methods do not write anything. They only return new strings. If the input is very long, they do not cut off the strings. We have noticed that it is much easier to use str. format () to output a square and cube table.
The basic usage of str. format () is as follows:
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!"
The characters in the brackets and brackets are replaced by parameters in format .. The numbers in parentheses are used to specify the position of the input object:
>>> print('{0} and {1}'.format('Kobe', 'James')) Kobe and James >>> print('{1} and {0}'.format('Kobe', 'James')) James and Kobe
If the keyword parameter is used in format (), their values point to the parameter using this name:
>>> print('The {thing} is {adj}.'.format(thing='flower', adj='beautiful')) The flower is beautiful.
The optional ':' and format identifiers can follow field name to better format:
>>> import math >>> print('The value of PI is {0:.3f}.'.format(math.pi)) The value of PI is 3.142.
Input an integer after ':' To ensure that the field has at least so many widths. This is useful when beautifying a table:
>>> table = {'Jack':4127, 'Rose':4098, 'Peter':7678} >>> for name, phone in table.items(): ... print('{0:10} ==> {1:10d}'.format(name, phone)) ... Peter ==> 7678 Rose ==> 4098 Jack ==> 4127
We can also unpack the parameters for formatting and output. For example, unpack a table as a keyword parameter:
Table = {'jack': 4127, 'Rose ': 4098, 'Peter': 7678} print ('Jack is {Jack}, Rose is {Rose }, peter is {Peter }. '. format (** table) # output: Jack is 4127, Rose is 4098, Peter is 7678.
Supplement:
The % operator can also be used to format strings. It uses the parameter on the left as a formatted string similar to sprintf (), and substitutes the parameter on the right as follows:
Import math print ('the value of PI is % 10.3f. '% math. pi) # output: The value of PI is 3.142.
Because this old format will eventually be removed from the Python language, you should use str. format () more ().
Appendix: text mode and binary mode
1. in Windows, in text mode, the row end identifier \ r \ n on Windows is converted to \ n by default, during writing, \ n is converted into \ r \ n. This hidden behavior is no problem for text files, but it may cause problems for binary data such as JPEG or EXE. Be careful when using these files in binary mode.
2. in Unix/Linux systems, the end identifier of the line is \ n, that is, the line feed is represented by \ n. Therefore, in Unix/Linux systems, there is no difference between the text mode and the binary mode.
The example readers described in this article can perform hands-on tests to help them better understand the Python basics.
Who can use python to help me write a small program, let the user input any 9 numbers, and then output the sorted results
I only write one function:
>>> Def littleFunc ():
Data = [] # initialization list
For I in range (9): # A for Loop
Num = int (raw_input ("input a number please:") # convert the control input to int
Data. append (num) # Put in the list
Data. sort () # sort
Print data # output
The python program extension is. py.
Program Execution result:
>>> LittleFunc ()
Input a number please: 1
Input a number please: 3
Input a number please: 5
Input a number please: 7
Input a number please: 8
Input a number please: 4
Input a number please: 9
Input a number please: 6
Input a number please: 2
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In python, how does one output horizontally-input Chinese characters vertically?
Try this. My name is python3.2.
#-*-Coding: UTF-8 -*-
Def vertical_print (s ):
Lines = s. strip ('. '). Split (',')
Lines. reverse ()
Print ('\ n'. join ([''. join (w) for w in zip (* lines)])
Vertical_print. ")
Use python 2.5:
#-*-Coding: UTF-8 -*-
Def vertical_print (s ):
Lines = s. strip ('. '. Decode ('utf8'). split (', '. decode ('utf8 '))
Lines. reverse ()
Print '\ n'. join ([''. join (w) for w in zip (* lines)])
S = "the day is full of mountains, the Yellow River enters the current, to thousands of miles, go to the next floor. ". Decode ('utf8 ')
Vertical_print (s)