Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7092

Re: new string formatting with local variables

References <BANLkTi=VUwFDv5otq=7CMngbWzHy3Fo50A@mail.gmail.com>
Date 2011-06-06 09:21 -0700
Subject Re: new string formatting with local variables
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.2491.1307377282.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Jun 6, 2011 at 9:15 AM, Jabba Laci <jabba.laci@gmail.com> wrote:
> Hi,
>
> I'd like to simplify the following string formatting:
>
> solo = 'Han Solo'
> jabba = 'Jabba the Hutt'
> print "{solo} was captured by {jabba}".format(solo=solo, jabba=jabba)
> # Han Solo was captured by Jabba the Hutt
>
> What I don't like here is this: "solo=solo, jabba=jabba", i.e. the
> same thing is repeated. In "solo=solo", the left part is a key and the
> right part is the value of a local variable, but it looks strange.
>
> I'd like something like this:
> print "{solo} was captured by {jabba}".format(locals())        # WRONG!
>
> But it doesn't work.
>
> Do you have any idea?

print "{solo} was captured by {jabba}".format(**locals()) # RIGHT

You must use prefix-** in the call to unpack the mapping as keyword arguments.
Note that using locals() like this isn't best-practice.

Cheers,
Chris
--
http://rebertia.com

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: new string formatting with local variables Chris Rebert <clp2@rebertia.com> - 2011-06-06 09:21 -0700
  Re: new string formatting with local variables Ben Finney <ben+python@benfinney.id.au> - 2011-06-07 10:11 +1000
    Re: new string formatting with local variables Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-06 18:31 -0600
    Re: new string formatting with local variables Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-06 18:38 -0600
    Re: new string formatting with local variables Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-07 03:57 +0000
      Re: new string formatting with local variables Ben Finney <ben+python@benfinney.id.au> - 2011-06-07 17:47 +1000

csiph-web