百分号和format方式使用

#Python的字符串格式化有两种方式: 百分号方式、format方式

#百分号使用
# #1.%s可以代表所有类型元素,%d只可以代表数字
# name1="i am %s,age is %d"%("小明",21)
# print(name1)#i am 小明,age is 21
#
# #2.以字典的形式赋值,
# tp3="i am %(name)s,age is %(age)d"%{"name":"小明","age":21}
#
# #3.浮点数据代表用%.2f,并可指定数据小数点几位
# tp4="percent %.2f"%3.1415926
# print(tp4)#percent 3.14
#
# #字典形式赋值浮点数,打印%需要写%%
# tp5="percent %(pp).2f%%"%{"pp":3.1415926}
# print(tp5)#percent 3.14%

#Format方式使用
#1.{}按照顺序取值,当给与的值为列表时,前面应加*
nm1 = "i am {},age {},{}".format("seven",18,"alex")
print(nm1)#i am seven,age 18,alex
nm1 = "i am {},age {},{}".format(*["seven",18,"alex"])
print(nm1)#i am seven,age 18,alex
#2.{1}按照序号取值,当给与的值为列表时,前面应加*
nm2 = "i am {1},age {0},{2}".format("seven",18,"alex")
nm3 = "i am {0}, age {1}, really {0}".format(*["seven",18])
print(nm2,nm3)
#3.按照键取值,当给与的值为字典时,前面应加**
nm4 = "i am {name}, age{age}, really {name}".format(**{"name":"seven","age":18})
nm5 = "i am {name}, age{age}, really {name}".format(name="seven",age=18)
print(nm4,nm5)
#索引取值
nm6 = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1,2,3],[11,22,33])
print(nm6)
#按照s,d,f代表元素类型取值
nm7 = "i am {:s}, age{:d}, money{:f}".format("seven",18,3.1415926)
nm8 ="i am {name:s}, age {age:d}".format(**{"name":"seven","age":18})
print(nm8)#打印结果:i am seven, age 18

#b代表2进制,o代表8进制,d代表10进制,x代表16进制,X代表16进制大写,%,显示百分比(默认显示小数点后6位)
tp12 = "numbers: {:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.87623,2)
print(tp12)#打印结果:numbers: 1111,17,15,f,F,1587.623000%

tp13 = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X},{0:%}".format(15)
print(tp13)#打印结果:numbers: 1111,17,15,f,F,1500.000000%

tp14 = "numbers:{num:b},{num:o},{num:d},{num:x},{num:X},{num:%}".format(num = 15)
print(tp14)#打印结果:numbers:1111,17,15,f,F,1500.000000%
posted @ 2020-05-09 16:46  小文-520  阅读(636)  评论(0编辑  收藏  举报