[Python-3000] format() method and % operator

Steven Bethard steven.bethard at gmail.com
Fri Aug 17 20:13:05 CEST 2007


On 8/17/07, Victor Stinner <victor.stinner at haypocalc.com> wrote:
> I didn't read the PEP nor all email discussions. So can you tell me if it
> would be possible to write simply:
>    "{} {}".format('Hello', 'World')

If you really want to write this, I suggest adding the following
helper function to your code somewhere::

    >>> def fix_format(fmt):
    ...     def get_index(match, indices=itertools.count()):
    ...         return str(indices.next())
    ...     return re.sub(r'(?<={)(?=})', get_index, fmt)
    ...
    >>> fix_format('{} {}')
    '{0} {1}'
    >>> fix_format('{} {} blah {}')
    '{0} {1} blah {2}'

That way, if you really want to bypass the precautions that the new
format strings try to take for you, you can do it in only four lines
of code.

STeVe
-- 
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
        --- Bucky Katt, Get Fuzzy


More information about the Python-3000 mailing list