python print的参数介绍

参考print的官方文档

print(...)
print(value, ..., sep=' ', end='
', 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.
  • 在python中,print默认向屏幕输出指定的文字,例如:

    >>>print('hello,world')
    hello world

  • print的完整格式为print(objects,sep,end,file,flush),其中后面4个为可选参数

    1. sep
      在输出字符串之间插入指定字符串,默认是空格,例如:
      >>>print("a","b","c",sep="**")
      a**b**c
    2. end
      print输出语句的结尾加上指定字符串,默认是换行( ),例如:
      >>>print("a",end="$")
      a$
      print默认是换行,即输出语句后自动切换到下一行,对于python3来说,如果要实现输出不换行的功能,那么可以设置end=''(python2可以在print语句之后加“,”实现不换行的功能)
    3. file
      将文本输入到file-like对象中,可以是文件,数据流等等,默认是sys.stdout
      >>>f = open('abc.txt','w')
      >>>print('a',file=f)
    4. flush
      flush值为True或者False,默认为Flase,表示是否立刻将输出语句输入到参数file指向的对象中(默认是sys.stdout)例如:
      >>>f = open('abc.txt','w')
      >>>print('a',file=f)
      可以看到abc.txt文件这时为空,只有执行f.close()之后才将内容写进文件。
      如果改为:
      >>>print('a',file=f,flush=True)
      则立刻就可以看到文件的内容
原文地址:https://www.cnblogs.com/jiduxia/p/7492037.html