Format函数的一些用法

Format格式化字符串

1.按序传入参数

实际上format()里面的会包装成为一个元组,若“”里面的{}里没有具体的参数,则按照顺序填入

print("my name is {}, my age is {}, my hobby is {}".format("alex", 18, "PingPangBall"))

结果:

my name isalex, my age is 18, my hobby is PingPangBall

2.按照{}里面的参数传入

print("my name is {0}, my age is {1}, my hobby is{2}".format("alex", 18, "PingPangBall"))
print("my name is {2}, my age is {1}, my hobby is{0}".format("alex", 18, "PingPangBall"))
print("my name is {1}, my age is {0}, my hobby is{2}".format("alex", 18, "PingPangBall"))

结果:

my name is alex, my age is 18, my hobby isPingPangBall
my name is PingPangBall, my age is 18, my hobby isalex
my name is 18, my age is alex, my hobby isPingPangBall

3.按照键值对来将值传入

print("my name is {name}, my age is {age}, my hobby is{hobby}".format(name = "alex", age = 18, hobby = "PingPangBall"))
print("my name is {name}, my age is {age}, my hobby is{hobby}".format(age = 18, hobby = "PingPangBall", name = "alex"))

结果:

my name is alex, my age is 18, my hobby isPingPangBall
my name is alex, my age is 18, my hobby isPingPangBall

4.指定传入的值的数据类型

print("s1 = {:d}, s2 = {:f}, s3 = {:b}, s4 = {:e}, s5 = {:o}, s6 = {:x}".format(12, 13, 14, 15, 16, 17))

结果:

s1 = 12, s2 = 13.000000, s3 = 1110, s4 = 1.500000e+01, s5 = 20, s6 = 11

5.多括号的情形

print("my name is {0}".format("alex"))
print("my name is {{0}}".format("alex"))
print("my name is {{{0}}}".format("alex"))
print("my name is {{{{0}}}}".format("alex"))
print("my name is {{{{{0}}}}}".format("alex"))

结果:

my name is alex
my name is {0}
my name is {alex}
my name is {{0}}
my name is {{alex}}

分析:由于{{}}可以转义为{},因此导致上述结果,也能直接看出来format()里面的参数不一定会传给前方字符串中

 

posted @ 2018-07-19 17:56  超级宇宙无敌乖宝宝  阅读(2819)  评论(0编辑  收藏  举报