Python 的 print 函数

     Python 2.x 系列已经停止维护了, python  3.x 系列正在成为主流,尽管有些项目还是python2.x 的,之后写Python 代码为了保持兼容性,还是尽量和Python 3 标准保持一致

     作为一个Python newbee 而言, python 2.x 和 3.x 的 最大的区别就是 print 从一个命令 变成了一个函数, raw_input() 被 input() 取而代之

      Python 最好的地方 之一就是文档很齐全,https://docs.python.org/3/  学习 python的好去处

      

      下方是 从命令行中 使用 help(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.

 

     1. print 函数的格式化输出

       1.1 符号占位符

 print("{name} is {age} years old.".format(name = "jack", age = 23)

       1.2 类似于C语言的占位符

          

  print("%s is %d years old." % ("jack", 23))

     2. print 函数重定向标准输出到文件

         

def write_log(string, file_name):
  try:
    with open(file_name, 'a') as log_file:
    print(string, file = log_file)
    log_file.close()
  except OSError as exc:
    tb = sys.exc_info()[-1]
    lineno = tb.tb_lineno
    filename = tb.tb_frame.f_code.co_filename
    print('{} at {} line {}.'.format(exc.strerror, filename, lineno))
    sys.exit(exc.errno)
def main():
   write_log("hello log!", "journal.txt")

if __name__ == '__main__':
   main()

     3. print 打印当前系统时间精确到毫秒, 需要导入时间包, 下方的代码参考 stackflow.com 的作答

     

    import  datetime
print('Timestamp: {%Y-%m-%d %H:%M:%S:%f}'.format(datetime.datetime.now()))

  

原文地址:https://www.cnblogs.com/wangshaodong/p/13511758.html