advanced string formatting vs template strings

前端 未结 4 553
南笙
南笙 2020-12-03 02:06

I was wondering if there is a advantage of using template strings instead of the new advanced string formatting?

4条回答
  •  悲哀的现实
    2020-12-03 02:59

    One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:

    "Hello, {first} {last}".format(first='Joe')
    

    raises:

    Traceback (most recent call last):
      File "", line 1, in 
    KeyError: 'last'
    

    But:

    from string import Template
    Template("Hello, $first $last").safe_substitute(first='Joe')
    

    Produces:

    'Hello, Joe $last'
    

    Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.

提交回复
热议问题