大爽Python入门教程 4-4 深入了解`print`

大爽Python入门公开课教案 点击查看教程总目录
以
学习读懂函数的过程。
1 内置函数
现在,让我们再来详细认识下print这个函数。print属于内置函数,built-in functions。
内置函数的官方文档为 Built-in Functions
如下图所示
在其中,点击print函数链接,跳转到print对应的说明。
截图如下
2 试读print官方文档
先尝试读下官方文档。
这里我们一句一句来读。
首先是函数声明,
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
先初步解读下这些形参
*objects: 接受不定数量的参数。sep=' ':sep默认值为' 'end='\n':end默认值为'\n'file=sys.stdout:sep默认值为sys.stdoutflush=False:flush默认值为False
然后继续往下
objectsto the text streamfile, separated bysepand followed byend.sep, end, file and flush, if present, must be given as keyword arguments.
将objects打印到文本流file中,使用sep来分割,最后接end。
如果存在sep、end、file或flush, 必须使用关键字参数来传参。
All non-keyword arguments are converted to strings like
str()`` does and written to the stream, separated bysepand followed byend. Bothsepandendmust be strings; they can also beNone, which means to use the default values. If noobjectsare given,print()will just writeend`.
所有非关键字参数(即位置参数),都会使用str()方法转换为字符串并写入流,使用sep来分割,最后接end。sep和end都必须是字符串;它们也可以是None,这意味着使用默认值。
如果没有传入objects,print() 将只输出end。
The
fileargument must be an object with awrite(string)method; if it is not present orNone,sys.stdoutwill be used.Since printed arguments are converted to text strings,
print()cannot be used with binary mode file objects.For these, use
file.write(...)instead.
file参数必须是具有 write(string)方法的对象; 如果它不存在或无,将使用 sys.stdout。
由于打印的参数被转换为文本字符串,print()不能用于二进制模式文件对象。
对于这些,请改用file.write(...)。
Whether output is buffered is usually determined by
file, but if theflushkeyword argument is true, the stream is forcibly flushed.
输出是否缓冲通常由file决定,但如果flush关键字参数为真,则流被强制刷新。
Changed in version 3.3: Added the
flushkeyword argument.
在 3.3 版更改: 添加了 flush 关键字参数。
说实话,我也没太读懂
flush。file也只是大概懂了。。。
3 大概总结
再回来看下函数头print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)file和flush太高级了,就不去理解了。
说下这三个
*objects: 接受所有的位置参数(非关键词参数),输出这些sep: 输出时,用sep作为分隔符,不指定则使用空格end: 输出时,用end来结尾,不指定则使用换行\n
4 代码示例
python">print("a", end=" ")print("b", end=" ")
print("c", end=" ")
print()
print("-"*20)
print(1, 2, 3, 4, sep="-")
print("-"*20)
words = list("abcdefg")
for word in words:
    print(word, end=",")
输出如下
a b c --------------------
1-2-3-4
--------------------
a,b,c,d,e,f,g,
以上是 大爽Python入门教程 4-4 深入了解`print` 的全部内容, 来源链接: utcz.com/z/386577.html

