python3.4 Methods for controlling user input and output

  • 2020-12-20 03:40:41
  • OfStack

1. The input

1. Function format: input()

2. Function function: Accept 1 standard input data, return string type. ctrl+z ends the input.

3. Example:


 The default input () : Wait 1 Input of any character 

str=input (' input a string:\n' ) : Accept input data as string Type to str . \n Wrap a line for the prompt. 

4. Accept more than one data entry, using the eval () function, and the interval must be comma


>>> lines
['', '', '', '84', '2', '3', '']
>>> a,b,c=eval(input())
1,2,3
>>> a
1
>>> c
3

5. One method for accepting multiple lines of input


>>> sen='end'  # As an end character 
>>> list2=[]

>>> for line in iter(input,ends):
line1=line.split(',')
list2.append(line1)


23,34
25,78
end
>>> list2
[['23', '34'], ['25', '78']]

2. The output

1. Function format: print ([object...]) ,sep=',end='\n',file= sys.stdout) (end defaults to enter, customizable symbol)

Example 2.

print(): Prints 1 blank line

Formatted output

#%x -- hex 106

#%d -- dec base 10

#%o -- oct base 8

#%s -- String

#%f - float floating-point number

Case 1:


>>> str1='the value is'
>>> num1=11
>>> print('%s%d'%(str1,num1))
the value is11

Example 2:


PI=3.1415926

print("PI = %10.3f" % math.pi) # The output PI =  3.142

print("PI = %-10.3f" % math.pi) # The output PI = 3.142

Example 3:


print("%.3s" %("abcde")) # The output abc

print("%.*s" %(4,"abcde")) # The output abcd

print("%10.3s" %("abcde")) # The output   abc( The total length of 10 , the character length is not enough to fill in the space )

Example 4: Print multiple lines


print("""  The content of your  """)  or  print('''  The content of your  ''')

Example 5: Print plain text without escape characters: print(r' content ') or print(R' content ')


print(r'abc\n') # Print string directly abc\n

Related articles: