• Python之路(五)-->> 格式化


    在Python中格式化的方式有两种,一种是%,另外一种是format()格式化。

    -----------------------------------------------------------(分隔线)--------------------------------------------------------------

    一、%格式化

      %s和%d,%s用来接收字符串,而%d用来接收数字的。例:

    tp = "i am %s,age %d" %('tom', 12)
    print(tp)
    
    #执行结果:i am tom,age 12

    从执行结果我们可以看出“tom”被替换到%s的位置,12被替换到了%d的位置。当然还有其他的比如:%f浮点数,%.2f%%百分比。例:

    tp1 = "percent %f" % 99.22354
    tp2 = "Percent %.2f%%" % 99.69545
    print(tp1)
    print(tp2)
    
    #执行结果:
    #                percent 99.223540
    #                Percent 99.70%        

    当然 % 还有其他形式的格式化,例:

    tp = "i am %(name)s,age %(age)d." % {"name": "tom", "age": 12}
    print(tp)
    
    #执行结果:i am tom,age 12.
    tp = "i am %(name)+20s,age %(age)d." % {"name": "tom", "age": 12}
    print(tp)
    
    #执行结果:i am                  tom,age 12.

    ------------------------------------------------------------(分隔线)--------------------------------------------------------------

    二、format()

      format是用{}来接收内容的,当然我们可以指定参数。例:

    tp = "i am {},age {}".format('tom', 12)
    tp1 = "i am {1},age {0}".format('tom', 12)
    print(tp)
    print(tp1)
    
    #执行结果:
    #                i am tom,age 12
    #                i am 12,age tom

      format()还可以用类似于键值对的方式来格式化,例:

    tp = "i am {name},age {age}".format(name = 'tom', age = 12)
    print(tp)
    
    #执行结果:i am tom,age 12
  • 相关阅读:
    东边日出西边雨
    ZooKeeper学习(一)了解ZooKeeper
    linux学习(七)文件打包和压缩命令
    linux学习(六)Linux yum 命令
    linux学习(五)Linux 文件与目录管理
    linux学习(四)Linux 文件基本属性
    linux学习(三)Linux 系统目录结构
    linux学习(二)认识Linux
    linux学习(一)认识阿里云
    多线程实战【面试题形式】
  • 原文地址:https://www.cnblogs.com/liuzhaoling/p/9790214.html
Copyright © 2020-2023  润新知