What is this syntax ?

Ben Finney ben+python at benfinney.id.au
Mon Jun 20 18:19:09 EDT 2011


Claudiu Popa <cpopa at bitdefender.com> writes:

> Hello,

(Please don't top-post. Instead, interleave your responses below each
quoted part you're responding to, as in this message. See also
<https://secure.wikimedia.org/wikipedia/en/wiki/Posting_style#Interleaved_style>.)

> Isn't this similar to php interpolation? And quite readable imo.
>
> >>> import string
> >>> template = string.Template("$scheme://$host:$port/$route#$fragment")
> >>> template.substitute(scheme="http", host="google.com", port="80", route="", fragment="")
> 'http://google.com:80/#'
> >>>

This style is so useful that a very similar system was proposed, and
accepted, in PEP 3101 as a method of the built-in types. It makes most
uses of the ‘string.Template’ class obsolete.

The text types (‘str’, ‘unicode’) now have a very similar capability as
part of the type. Works in Python 2.6 or later, and Python 3 or later.

    >>> template = "{scheme}://{host}:{port}/{route}#{fragment}"
    >>> template.format(scheme="http", host="google.com", port="80", route="", fragment="")
    'http://google.com:80/#'

“This method of string formatting is the new standard in Python 3.0, and
should be preferred to the % formatting described in String Formatting
Operations in new code.”

<URL:http://docs.python.org/library/stdtypes.html#str.format>

-- 
 \                “Room service? Send up a larger room.” —Groucho Marx |
  `\                                                                   |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list