python的输出

输出

在python中可使用内置函数print()将结果输出到IDLE或标准控制台上(就是那个cmd黑窗口,也可以理解为显示器上)。

先来查询一下帮助

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

 

print()的用法

输出内容可以是数字、字符串、运算表达式

a = 100
b = 5
print('go big or go home!')
print(9)
print(a*b)
print(a,b,'要么出众,要么出局') #输出多个变量使用逗号分隔

 

扩展用法

print(' ',sep=' ',end=' ')

#补充
age = 18
gender ='boy'
print(name,age,gender) 
print(name,age,gender,sep='#')#sep设置分隔符以#分隔
print('hello\nkitty')
print('AAA',end=' ') #\n换行符,print函数默认结尾为\n,可使用end设置
print('BBB',end='')
------------执行脚本--------------------------
E:\python>python test.py
小白 18 boy #输出为空格分隔
小白#18#boy #输出为#分隔
hello #\n换行
kitty
AAA BBB #将默认换行符改为'',则不换行

 

ASCII码

是美国信息交换标准码,在编程中可以使用ASCII码表示字母、数字、符号。

因为计算机是老外发明的,所以最早只有127个字母被编码到计算机中,也就是字母、数字跟一些符号。

附表:常用字符与ASCII码对照表

#通过ASCII码显示字符,需要使用chr函数转换
print(chr(97)) #输出a
print(chr(65)) #输出A
print(chr(43)) #输出+

 

Unicode编码

python3内部字符编码,可以用来表示其他语言,中文,俄文,日语等字符。

采用双字节16位进行编号,可表示65536个字符。

print('\u4e2d\u56fd') #输出为中国

 

案例

将下面一句话输出到d盘mr.txt文件中

fp = open(r'D:\mr.txt','a+') #打开文件
print('go big or go home',file=fp) #输出到文件中
fp.close() #关闭文件

 

案例2

输出当前日期跟时间

import datetime
print('当前年份:' +str(datetime.datetime.now().year)) #输出为 当前年份:2020
#输出当前日期时间
print('当前日期时间:'+datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')) 
#输出为 当前日期时间:20-11-09 14:33:32

 

练习题答案

一个\t等于4个空格

print('亲爱的xxx:\n','请点击链接激活用户:激活用户',sep='\t')
---------------执行脚本--------------------
亲爱的xxx:
        请点击链接激活用户:激活用户

 

学习来自:B站大学 P11

《python从入门到项目实践》明日科技 第三章

posted @ 2020-10-24 00:50  努力吧阿团  阅读(755)  评论(0编辑  收藏  举报