在编程实践中,print 的使用频率非常高,特别是程序运行到某个时刻,要检测产生的结果时,必须用 print 来打印输出。
关于 print 函数,前面很多地方已经提及过,可用于写入标准输出。现在,是时候该深入了。
注意:这里强调的是“print 函数”,而不是“print 语句”。
深入print
在 Python 2.x 中,print 是一个语句,但是在 Python 3.x 中,它是一个函数。如果 2.x 和 3.x 都使用过,你就会发现差异有多么大。
进入 3.x 的交互式 shell,尝试使用“print 语句”:
[wang@localhost~]$python Python3.5.2(default,Mar292017,11:05:07) [GCC4.8.520150623(RedHat4.8.5-11)]onlinux Type"help","copyright","credits"or"license"formoreinformation. >>> >>>print'Python' ... SyntaxError:Missingparenthesesincallto'print'
对于大多数人来说,这个错误信息再熟悉不过了。正如上面所提到的那样,print 是 3.x 中的一个函数,与其他函数一样,参数应该被圆括号括起来
>>>print('Python') Python
print函数
要了解 print 函数的用途,可以使用 help() 来寻求帮助:
>>>help(print) ... Helponbuilt-infunctionprintinmodulebuiltins: print(...) print(value,...,sep='',end='\n',file=sys.stdout,flush=False) Printsthevaluestoastream,ortosys.stdoutbydefault. Optionalkeywordarguments: file:afile-likeobject(stream);defaultstothecurrentsys.stdout. sep:stringinsertedbetweenvalues,defaultaspace. end:stringappendedafterthelastvalue,defaultanewline. flush:whethertoforciblyflushthestream.
将对象输出到文本流文件,由 sep 分开,然后以 end 结束。如果 sep、end、file 和 flush 出现,则必须以关键字参数的形式指定。
不使用关键字参数
print 函数可以打印任意数量的值(value1, value2, …),这些值由逗号分隔。
>>>age=18 >>> >>>print('age',age) age18
很容易发现,两个值之间有一个分隔符 – 空格(默认值),这取决于 sep。
分隔符
>>>print('age',age,sep='')#去掉空格 age18 >>> >>>print('www','python','org',sep='.')#以.分割 www.python.org原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容