【Python】【Head First Python】【chapter1】2 - sys.stdout 和 print 的区别

sys.stdout 和 print 的区别

  • 首先,通过

      help(print)
  • 得到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()函数的几个参数:
    • value是值的意思,可以传出字符串、数字、列表等
    • sep默认为空,即打印的时候两个值之间的填充
    • end默认是换行,当不想要换行显示的时候可以修改默认值
    • file表示了print和sys.stdout的关系,print函数默认已经是标准化输出
    • flush是刷新的意思
    • 这里有一篇有趣的文章,通过调整flush参数实现动态图的效果python的print(flush=True)实现动态loading......效果
  • 更多资料可参考python的print与sys.stdout
  • 例如

      list_1 = [1, 2, 3]
      for i in list_1:
          print(i)
      for j in list_1:
          print(j, end='')
  • 运行得到,这个是end参数的作用

      1
      2
      3
      123
  • 例如
    d = {'a': 1, 'b': 2, 'c': 3}
    for k,v in d.items():
    print(k, v, sep='**')

  • 运行得到,这个是sep参数的作用

      a**1
      b**2
      c**3

猜你喜欢

转载自www.cnblogs.com/chenxianbin/p/10597755.html