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


Groups > comp.lang.python > #7107 > unrolled thread

Re: new string formatting with local variables

Started byEric Snow <ericsnowcurrently@gmail.com>
First post2011-06-06 14:22 -0600
Last post2011-06-06 14:22 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: new string formatting with local variables Eric Snow <ericsnowcurrently@gmail.com> - 2011-06-06 14:22 -0600

#7107 — Re: new string formatting with local variables

FromEric Snow <ericsnowcurrently@gmail.com>
Date2011-06-06 14:22 -0600
SubjectRe: new string formatting with local variables
Message-ID<mailman.2504.1307391772.9059.python-list@python.org>
On Mon, Jun 6, 2011 at 10: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?
>

You were close:

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

This will turn locals() into keyword args for the format call.  The
tutorial has a good explanation on argument unpacking [1].

-eric

[1] http://docs.python.org/dev/tutorial/controlflow.html#unpacking-argument-lists


> Thanks,
>
> Laszlo
> --
> http://mail.python.org/mailman/listinfo/python-list
>

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web