字符串格式化

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

 

posted @ 2019-07-23 01:33  小白cwt  阅读(865)  评论(0编辑  收藏  举报