• 字符串格式化


    1.用%进行字符串格式化:%(key)flags(对齐方式,如+表右对齐)  width(步长)   .precision(保留小数点后几位)   type (数据类型)

    (1):s表示输入的是字符串类型但就算是其它类型依然可以运行,d表示的是整数字(不可以输入其它),f 表示的小数

    a = "He is %s, He very %s" %("chenweitao","handsome")
    b = "He age is %d"  %(20)
    c = "He is %.2f  m"   %(1.745)
    print(a)
    print(b)
    print(c)
    
    
    》》》He is chenweitao, He very handsome
    》》》He age is 20
    》》》He is 1.75  m

    补充:若要输百分号可以写》》》》》%%

    2.用  .format()  进行字符串格式化:

    a = "He is {}, He very {}"
    b = "He age is {}"
    c = "He is {} m"
    d = a.format("chenweitao","handsome")
    e = b.format(20)
    f = c.format(1.75)
    print(d)
    print(e)
    print(f)
    
    
    》》》He is chenweitao, He very handsome
    》》》He age is 20
    》》》He is 1.75 m
    a = "He is {2}, He very {0} and {1}"
    b = a.format("handsome","outgoing","chenweitao")
    print(b)
    
    >>>He is chenweitao, He very handsome and outgoing

    format 中的值也可以填元组,列表或者是字典,但必须化为》》》*(元组),*[列表]

                           》》》**{字典}

     因为当format中的值是字符串是,format本身会为其加个[  ]

    a = "He is {}, He very {} and {}"
    b = a.format(*["chenweitao","handsome","outgoing"])
    print(b)
    
    
    >>>He is chenweitao, He very handsome and outgoing
    a = "He is {name}, He very {tezheng1} and {tezheng2}"
    b = a.format(**{"name":"chenweitao","tezheng1":"handsome","tezheng2":"outgoing"})
    print(b)
    
    >>>>He is chenweitao, He very handsome and outgoing

    补充:{:b}>>>表示将输入的值转化为二进制

      {:o}>>>表示将输入的值转化为八进制

      {:x}>>>表示将输入的值转化为16进制(可以分大小写)

      {:%}>>>表示将输入的值转化为百分号且默认保留小数点后6位

    b = "He age is {:b}"
    c = b.format(10)
    print(c)
    
    
    
    》》》He age is 1010
  • 相关阅读:
    PHP运行及语句及逻辑
    数据库基础,表及SQL语句
    php后台修改人员表信息
    php后台增加删除修改跳转页面
    用PHP访问数据库
    php登录注册页面及加载
    php做登录注册页面及加载
    实现基于物理的渲染
    Tile-Based Deferred Rendering
    矩阵基础 2
  • 原文地址:https://www.cnblogs.com/chenweitao/p/11229415.html
Copyright © 2020-2023  润新知