zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    另一种遍历Map的方式: Map.Entry 和 Map.entrySet()
    mycat 插入语句导致的一个Dobbo问题
    Json数据处理
    List与字符串转换
    MySQL中四舍五入的实现
    java连接mysql :No Suitable Driver Found For Jdbc 解决方法
    Linux中printf格式化输出
    bat隐藏文件夹
    Python 3.5.2建立与DB2的连接
    Python 爬虫实例
  • 原文地址:https://www.cnblogs.com/liuzhaoling/p/9790214.html
Copyright © 2011-2022 走看看