Python进阶之路 5.2.2 模板字符串

    xiaoxiao2023-11-07  147

    5.2.2 模板字符串

    在string模块中提供了一个用于格式化字符串的Template类,该类的功能是用同一个值替换所有相同的格式化参数。Template类的格式化参数用美元符号($)开头,后面跟着格式化参数名称,相当于变量名。在格式化时,需要使用Template类的substitute方法,该方法用于指定格式化参数对应的值。

    from string import Template template = Template('$s $s $s') template.substitute(s = 'Hello') #这种参数被称为关键字参数

    在上面的代码中,通过Template类的构造方法传入了一个格式化字符串,在这个格式化字符串中包含了三个’s’,然后调用了substitute方法格式化这个字符串,该方法指定了s参数值为’Hello’,最后的替换结果是’Hello Hello Hello’,也就是说,在格式化字符串中,有多少个’s’,就替换多少个’s’。substitute方法还可以通过字典设置格式化参数的值。

    [例 5.4] 本例使用Template格式化字符串,当格式化参数是一个字符串的一部分时,需要用一对大括号({ })将格式化参数变量括起来。

    #引用string模块中的Template类 from string import Template template1 = Template('$s是我最喜欢的编程语言,$s非常容易学习,而且$s的功能很强大。') #指定格式化参数s的值是Python print(template1.substitute(s='Python')) #当格式化参数是一个字符串的一部分时,为了和字符串的其他部分区分开,需要用一对大括号将格式化参数变量括起来 template2 = Template('${s}stitute') print(template2.substitute(s='sub')) template3 = Template('$dollar$$相当于多少$pounds') #替换两个格式化参数变量 print(template3.substitute(dollar=20,pounds='英镑')) template4 = Template('$dollar$$相当于多少$pounds') data = {} data['dollar'] = 100 data['pounds'] = '英镑' #使用字典指定格式化参数 print(template4.substitute(data))

    输出结果:

    Python是我最喜欢的编程语言,Python非常容易学习,而且Python的功能很强大。 substitute 20$相当于多少英镑 100$相当于多少英镑
    最新回复(0)