zoukankan      html  css  js  c++  java
  • 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()))

      

  • 相关阅读:
    Ubuntu12.04配置永久静态ip地址
    linux shell 命令获取字符串/文件的MD5值
    设置VMware中Kali 共享文件夹
    tomcat的一些优化及报错
    用Toad for Oracle创建数据库表空间和用户
    linux远程Windows服务器
    linux查询及添加用户
    AJAX
    Cookie和Session
    Django-中间件
  • 原文地址:https://www.cnblogs.com/wangshaodong/p/13511758.html
Copyright © 2011-2022 走看看