11月07, 2016

Python中的模板字符串

用过ES6的同学都知道,使用ES6的模板字符串非常方便,比如下面的代码所示:

const print = () =>{
    const name = "larry";
    const age = 20;
    const fullInfo = `name is ${name}, age is ${age}`;
    console.log( fullInfo ); // 控制将打印出:name is larry, age is 20
}

在Python中,我们怎么来处理这种字符串呢? 个人简单总结了下,有以下4种方式。

使用%表达式

def do_print():
    str = "name is %s, age is %s"
    print( str %("larry", 20) )

do_print()

使用format方法

def do_print():
    str = "name is {}, age is {}"
    print( str.format("larry", 20))

    str = "name is {name}, age is {age}"
    print( str.format(name = "larry", age = 20))

do_print()

使用用string.Template模块

from string import Template

def do_print():

    t = Template("name is ${name}, age is ${age}" )
    print( t.substitute(name = "larry", age = 20) ) # name is larry, age is 20
    print( t.safe_substitute(name = "larry")) # 使用更安全的字符串替换,避免出现异常。name is larry, age is ${age}

do_print()

使用Jinja2模板引擎

from jinja2 import Template

def do_print():

    t = Template("name is {{name}}, age is {{age}}" )
    print( t.render(name = "larry", age = 20) ) # name is larry, age is 20

    t = Template("name is {{name | upper}}" )
    print( t.render(name = "larry")) # name is LARRY

do_print()

总结

如果只是简单的字符串处理,可以考虑用方法1、2、3、4, 如果比较复杂的字符串处理,比如需要对字符串做格式化或者转换, 就可以考虑用更为强大的Jinja2, 中文文档可以点这里

本文链接:http://www.asyncoder.com//post/python-template-string.html

-- EOF --

Comments