Python input () and print () input and output function application example notes

1. Input input function
Use the input function to wait for user input from the keyboard
. Anything input by the user is considered by Python as a string.
If you need other types, you need a conversion function.

float			字符串或者整数-->浮点型
int				字符串或浮点型-->整数型
str				数字-->字符串
eval 			数字-->实数
chr				ASCII值-->ASCII字符
hex				整数-->十六进制的字符串
long			字符串-->长整型
oct				整数-->八进制的字符串
ord				ASCII字符-->ASCII值

>>> a = input("请输入:")			#括号内可写需要输入的提示内容(要有引号)
请输入:Hello World!
>>> a
'Hello World!'

>>> b= int(input(("请输入整数:")))	  #int()将输入的字符串类型转换为整数类型
请输入整数:50
>>> b
50

c = float(input("请输入一个数:"))		#float()将输入的字符串类型转换为浮点类型
请输入一个数:45.6
>>> c
45.6

2. The print() output function or print function
python has multiple output methods:
1. Variables or expressions

>>> 4+6
10
>>> x = 10
>>> y = 20
>>> z = x + y
>>> y-x
10
>>> z
30

2. Using the write() method of the file object, the standard output file can be referenced with sys.stdout

3. Use print() to output the values ​​of all data types in Python.
The syntax of the function:

print(*objects, sep='', end='\n', file=sys.stdout)
objects-represents the output objects. When outputting multiple objects, they need to be separated by, (comma).

sep-used to separate multiple objects.

end-used to set the ending. The default value is newline \n, we can change to other characters.

file-the file object to be written.

>>>x,y,z = 1,'a','$'
>>>print("The values are", x, y, z)	#打印一系列以空格分隔的值以逗号分隔,打印字符串用引号
The values are 1 a $
>>>print("The values are", x, y, z, spe=',')#输出指定分隔符
>>>The values are,1,a,$

>>> print('\n'*num)						#打印空行(num为空行数)

Redirect output to a file

Example 1

>>> f=open('f.txt','w')			
>>> import sys
>>> old=sys.stdout			#将当前系统输出存储到一个临时变量中
>>> sys.stdout=f				#输出重定向到文件
>>> print('Hello World!',file=f)
>>> sys.stdout=old			#还原原系统输出
>>> f.close()
>>> f1=open('f.txt','r')
>>> print(f1.read())
Hello World!

Example 2

# 在当前文件夹创建文件test.txt,并写入内容
>>> with open('test.txt', 'w') as fp:
    print('Hello world', file=fp)

Example 3

>>> fp = open('test.txt', 'w')
# 此时并没有真正把内容写入文件,而是写入了缓冲区
>>> print('Hello world', file=fp)
	# 关闭文件,把缓冲区里的内容写入文件
>>> fp.close()
>>> fp = open('test.txt', 'w')
# 强制把缓冲区里的内容写入文件
# 不用关闭文件即可写入
>>> print('Hello world', file=fp, flush=True)
>>> fp.close()

Data formatted output

%s character string (displayed by str())
%r character string (repr()) display
%c single character and its ASCII code
%u unsigned integer
%b binary integer
%d %i decimal integer
%o octal integer
%x Hexadecimal integer
%e exponent (base write e)
%E exponent (base write E)
%f,%F floating point
%g If the exponent is greater than -4 or less than the precision value, it is the same as e, otherwise it is the same as f
%G is the same as E if the exponent is greater than -4 or less than the precision value, otherwise it is the same as F.
%% character%
%p format the address of the variable with a hexadecimal number

>>> abc ="abcdefg"
>>> x = len(abc)
>>> print("Teh length of %s is %d" %(s,x))
>>> print("The length of %s is %d" %(abc,x))
The length of abcdefg is 7

>>> PI = 3.1415926
>>> print('%10.3f'%PI)	#字段宽10,精度3
     3.142
>>> print("PI = %.*f" %(3,PI))		#用*从后面的元组中读取字段宽度或精度
PI = 3.142
>>> print("PI = %*.3f" %(6,PI))
PI =  3.142

Conversion flag:
-means left-justified;
+ means to add a sign before the value;
*define the width or decimal point precision
mn m is the minimum total width of the display, n is the number of digits after the decimal point

""(Blank character) means to reserve a space () before the positive number;
0 means that the converted value is filled with 0 if the number of digits is not enough.

>>> print("---%-10.3f---" %PI)
---3.142     ---
>>> print("---%+.3f---" %PI)
---+3.142---
>>> print("---%010.3f---" %PI)
---000003.142---

>>> for i in range(0,5):
... 	print(i,end='')
... 
01234>>> for i in range(0,5):
... 		print(x,end=',')
... 
0,1,2,3,4,>>> 

format formatted output

The syntax format of the format() method is as follows:
str.format(args)
str is used to specify the display style of the string;
args is used to specify the items to be formatted, if there are multiple items, separate them with commas

When creating a display style template, you need to use {} and: to specify placeholders. The complete syntax format is:
{[index][: [[fill] align] [sign] [#] [width] [.precision] [type]]}

The parameters enclosed in [] in the format are optional parameters
index: the format set later should be applied to the number of data in args. The index value of the data starts from 0 and is automatically assigned according to the order of the data in args by default.
fill: characters to fill in the blank. Note that when the padding character is a comma (,) and acts on an integer or floating point number, the integer (or floating point number) will be output in a comma separated form, for example (1000000 will output 1,000,000).
align: Specify the alignment of the data, the specific alignment is shown in Table 1.

<	数据左对齐。
>	数据右对齐。
=	数据右对齐,同时将符号放置在填充内容的最左侧,该选项只对数字类型有效。
^	数据居中,此选项需和 width 参数一起使用。

sign: Specify whether there is a signed number, the value of this parameter and the corresponding meaning

+			正数前加正号,负数前加负号。
-			正数前不加正号,负数前加负号。
空格		正数前加空格,负数前加负号。
#			对于二进制数、八进制数和十六进制数,使用此参数,各进制数前会分别显示 0b、0o、0x前缀;反之则不显示前缀。

width: Specify the width of the output data.
.precision: Specify the number of decimal places to keep.
type: Specify the specific type of output data

s			对字符串类型格式化。
d			十进制整数。
c			将十进制整数自动转换成对应的 Unicode 字符。
e 或者 E 	转换成科学计数法后,再格式化输出。
g 或 G		自动在 e 和 f(或 E 和 F)中切换。
b			将十进制数自动转换成二进制表示,再格式化输出。
o			将十进制数自动转换成八进制表示,再格式化输出。
x 或者 X	将十进制数自动转换成十六进制表示,再格式化输出。
f 或者 F	转换为浮点数(默认小数点后保留 6 位),再格式化输出。
%			显示百分比(默认显示小数点后 6 位)。


>>> print("{}:计算机{}的CPU占用率为{}%".format("2020-08-31","c",10))
2020-08-31:计算机c的CPU占用率为10%
>>>print("货币形式:{:,d}".format(1000000))
货币形式:1,000,000
>>>print("科学计数法:{:E}".format(1200.12))
科学计数法:1.200120E+03
>>>print("100的十六进制:{:#x}".format(100))
100的十六进制:0x64
>>>print("0.01的百分比表示:{:.0%}".format(0.01))
0.01的百分比表示:1%

Commonly used related conversion functions

abs(number), returns the absolute value of the number

float(object), convert strings and numbers to floating point numbers

int(object), convert strings and numbers to integers

str(object), convert the value to a string

cmath.sqrt(number), returns the square root, can also be applied to negative numbers

help(), provide interactive help

math.ceil(number), the up-in integer of the return number, the type of the return value is a floating-point number

math.floor(number), the rounded integer of the return number, the type of the return value is a floating point number

math.sqrt(number), returns the square root not applicable to negative numbers

pow(x,y[.z]), returns X to the power of y (if there is z, the modulus of z is taken)

repr(object), the string identification form of the return value

round(number[.ndigits]), round the number according to the given precision

Summary of escape characters
Insert picture description here

	\    续行符

In Unix systems, there is only "<newline>" at the end of each line, that is, "\n";

In Windows system, the end of each line is "<carriage return><line feed>", that is, "\r\n";

In Mac system, the end of each line is "<Enter>", that is, "\r".

A direct consequence is that if a file under Unix/Mac is opened in Windows, all text will become one line; and if a file in Windows is opened under Unix/Mac, there may be an extra ^M at the end of each line. symbol.

Windows uses carriage return + line feed (CR+LG) to represent the next line (also known as PC format)
UNIX uses line feed (LF) to represent the next line,
MAC machines use carriage return (CR) to represent the next line

Guess you like

Origin blog.csdn.net/qq_41952762/article/details/108149616