Python进阶之路 5.2.3 字符串的format方法

    xiaoxiao2023-11-10  156

    5.2.3 字符串的format方法

    字符串本身也有个format方法用于格式化当前的字符串。这个format方法和前面讲的格式化操作符(%)不太一样。字符串格式化参数并不是用百分号(%)表示,而是用一对大括号({}) ,而且支持按顺序指定格式化参数值和关键字格式化参数。例如,下面代码通过format方法按顺序为格式化字符串指定了参数值。

    print('{} {} {}'.format(1,2,3)) #输出结果:1 2 3

    可以看到,上面的代码在字符串中指定了三对空的大括号,这代表三个格式化参数,不需要指定数据类型,可以向其传递Python语言支持的任何值。通过format方法传入三个值(1,2,3),这三个值会按顺序替换格式化字符串中的三对空的大括号。

    命名格式化参数是指在一对大括号中指定一个名称,然后调用format方法时也要指定这个名称。

    print('{a} {b} {c}'.format(a = 1,c = 2,b = 3)) #输出结果:1 3 2

    上面的代码在三对大括号中分别添加了’a’,‘b’,‘c’。通过format方法指定了这三个关键字参数的值。可以看到,并没有按顺序指定关键字参数的值。这也是使用关键字参数的好处,只要名字正确,format参数的顺序可以任意指定。当然,顺序方式和关键字参数方式可以混合使用,而且还可以指定顺序方式中格式化参数从format方法提取参数值的顺序,甚至可以取format方法参数值的一部分。

    [例 5.5] 本例演示format方法的一些常用使用方式,分别使用一对大括号"{}"、命名格式化参数和顺序格式化参数3种方式格式化字符串。

    #包含了2个空的大括号,format方法需要按顺序指定格式化参数值 s1 = 'Today is {}, the temperature is {} degrees.' #format方法的第1个参数值对应s1的第1对大括号,第2个参数值对应s1的第2对大括号 print(s1.format('Saturday',28)) #输出结果:Today is Saturday, the temperature is 28 degrees. #包含了2个命名格式化参数,一个是(week),另一个是(degree) s2 = 'Today is {week}, the temperature is {degree} degrees' #format方法的第1个参数指定了{degree}的值,第2个参数值指定了{week}的值 #可以将degree和week调换,s2.format(week='Sunday',degree=24) print(s2.format(degree=24,week='Sunday')) #输出结果:Today is Sunday, the temperature is 24 degrees #混合了顺序格式化参数和关键字格式化参数两种方式 s3 = 'Today is {week},{},the {} temperature is {degree} degrees.' #format方法的参数,前面应该是按顺序传递的格式化参数值,后面是关键字格式化参数值,顺序不能调换 #这是错误的:s3.format(degree=24,'aaaaa',12345,week='Sunday') print(s3.format('aabb',123456,degree=24,week='Sunday')) #输出结果:Today is Sunday,aabb,the 123456 temperature is 24 degrees. #为顺序格式化参数指定了从format方法获取参数值的顺序,{1}表示从format方法的第2个参数取值 #{0}表示从format方法的第1个参数取值 s4 = 'Today is {week}, {1},the {0} temperature is {degree} degrees.' print(s4.format('aaabbb',12345,week='Sunday',degree=24)) #format方法的第1个参数是aaabbb,第2个参数是12345 #输出结果:Today is Sunday, 12345,the aaabbb temperature is 24 degrees. #定义了一个列表 fullname = ['Bill','Gates'] #{name[1]}取fullname列表中的第2个值(Gates) #format方法通过关键字参数,为name名字指定了fullname列表 print('Mr {name[1]}'.format(name=fullname)) #输出结果:Mr Gates #导入math模块 import math #访问math模块中的"__name__"变量来获取模块的名字,访问math模块中的pi变量获取pi的值 s5 = 'The {mod.__name__} module defines the value {mod.pi} for PI' #format方法为mod关键字参数指定了math模块 print(s5.format(mod=math)) #输出结果:The math module defines the value 3.141592653589793 for PI

    输出结果:

    Today is Saturday, the temperature is 28 degrees. Today is Sunday, the temperature is 24 degrees Today is Sunday,aabb,the 123456 temperature is 24 degrees. Today is Sunday, 12345,the aaabbb temperature is 24 degrees. Mr Gates The math module defines the value 3.141592653589793 for PI
    最新回复(0)