How do I use Python to easily expand variables to strings?

前端 未结 4 1182
一个人的身影
一个人的身影 2021-02-05 07:52

What\'s a nice idiom to do this:

Instead of: print \"%s is a %s %s that %s\" % (name, adjective, noun, verb)

I want to be able to do something to th

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 08:02

    use string.Template

    >>> from string import Template
    >>> t = Template("$name is a $adjective $noun that $verb")
    >>> t.substitute(name="Lionel", adjective="awesome", noun="dude", verb="snores")
    'Lionel is a awesome dude that snores'
    

提交回复
热议问题