Print:打印标准输出的函数
格式:print()
print()函数有三个参数

value用户需要输出的信息sep多个要输出信息之间的分隔符,默认是空格end输出信息结尾处的默认添加的符号,默认为换行符

函数参数使用举例:

>>>num1=2>>>str1='words'>>>print(num1,str1)2 words

默认2与words之间有一个空格,输出完成之后有一个回车
使用了@作为分割符

>>>print(num1,str1,sep='@')2@words

使用&作为结尾

>>>print(num1,str1,sep='@',end='&')2@words&

其实print函数还有一个参数file,通常print函数都是stdout方式输出,但是如果需要将输出结果重定向到一个文件可以使用file参数

f=open("d:\\new.txt","w")for i in range(6):print("new line",file=f)

此时在d盘更目录下会自动创建一个new.txt文件,并打印6行new line在其中。

【Case1】

直接输出打印内容

>>>print("This is a new word.")This is a new word.

如果内容过长,可以使用\作为换行符

>>>print("This is a new \word")This is a new word

【Case2】

使用变量打印内容

>>> a="This is a new word.">>> print(a)This is a new word.

【Case3】

使用三引号作为格式打印

>>>str="""Thisisanewword.""">>>print(str)Thisisanewword.

【Case4】

除了使用三引号作为格式化输出,还有两种格式化输出的方式%和.format



使用%占位符格式化打印
主要使用的占位符有:
%s 字符串
%r 字符串
%d 十进制整数
%i 十进制整数
%f 浮点数


>>>str1='world'>>>print('hello %s' %'world')hello world

>>>print('hello %s' %str1)hello world

>>>str='abc'>>>print("%s" %str)abc>>> print("%s" %str.title())Abc

>>>print('hello %r' %str1)hello 'world'


>>>num1=300>>>print ('the number is','%d' %num1)the number is 300

>>>print ('the number is','%i' %num1)the number is 300

>>> num2=30>>> name='John'>>> print('He is %s, he is %d years old.' %(name,num2))He is John, he is 30 years old.


其它占位符:
%c 单个字符
%b 二进制整数
%o 八进制整数
%x 十六进制整数
%e 指数 (基底写为e)
%E 指数 (基底写为E)
%F 浮点数,与上相同
%g 指数(e)或浮点数 (根据显示长度)
%G 指数(E)或浮点数 (根据显示长度



使用format()方法格式化打印


>>> str='''Username={uname}Id={id}Phone={tel}'''.format(uname='Jone',id='123',tel='138***')>>> print(str)Username=JoneId=123Phone=138***

>>> str2="{0}".format("abc")>>> print(str2)abc

>>> str='''username={0}Id={1}Phone={2}'''.format('Jone','123','138***')>>> print(str)username=JoneId=123Phone=138***


【Case5】

转义字符
常用转义字符:
/t 输出一个横向指标符
/n 输出一个换行符
/v 输出一个纵向制表符
/f 输出一个换页
/r 输出一个回车