zoukankan      html  css  js  c++  java
  • 字符串格式化

    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
  • 相关阅读:
    centos和ubuntu配置路由的三种方式
    程序包编译安装
    逻辑卷磁盘管理和dd命令
    linux磁盘管理
    CDOJ 1269 ZhangYu Speech 数组处理
    poj 2236 Wireless Network 并查集
    poj 1182 食物链 并查集
    POJ 2109 Power of Cryptography 数学题 double和float精度和范围
    CDOJ 1264 人民币的构造 区间问题+数论
    CDOJ 1263 The Desire of Asuna 贪心
  • 原文地址:https://www.cnblogs.com/chenweitao/p/11229415.html
Copyright © 2011-2022 走看看