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


Groups > comp.lang.python > #60559

Re: Python String Formatting - passing both a dict and string to .format()

References <fc656c78-a32b-4f85-8da6-a5c7abf1edfa@googlegroups.com>
From Chris Kaynor <ckaynor@zindagigames.com>
Date 2013-11-26 16:21 -0800
Subject Re: Python String Formatting - passing both a dict and string to .format()
Newsgroups comp.lang.python
Message-ID <mailman.3266.1385511717.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Tue, Nov 26, 2013 at 4:01 PM, Victor Hooi <victorhooi@gmail.com> wrote:

> Hi,
>
> I'm trying to use Python's new style string formatting with a dict and
> string together.
>
> For example, I have the following dict and string variable:
>
>     my_dict = { 'cat': 'ernie', 'dog': 'spot' }
>     foo = 'lorem ipsum'
>
> If I want to just use the dict, it all works fine:
>
>     '{cat} and {dog}'.format(**my_dict)
>     'ernie and spot'
>
> (I'm also curious how the above ** works in this case).
>

> However, if I try to combine them:
>
>     '{cat} and {dog}, {}'.format(**my_dict, foo)
>     ...
>     SyntaxError: invalid syntax
>

Here you almost have it right. If you flip the arguments around to look
like:
    '{cat} and {dog}, {}'.format(foo, **my_dict)
it will work as you expect.

The issue is that you cannot specify positional arguments (foo) after
keyword arguments (**my_dict).

In the code you tried, what Python is doing is:
    '{cat} and {dog}, {}'.format(cat=ernie, dog=spot, foo)
which, if tried, provides the nicer error message of "SyntaxError:
non-keyword arg after keyword arg".

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


Thread

Python String Formatting - passing both a dict and string to .format() Victor Hooi <victorhooi@gmail.com> - 2013-11-26 16:01 -0800
  Re: Python String Formatting - passing both a dict and string to .format() Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-27 00:14 +0000
  Re: Python String Formatting - passing both a dict and string to .format() Michael Torrie <torriem@gmail.com> - 2013-11-26 17:21 -0700
  Re: Python String Formatting - passing both a dict and string to .format() Chris Kaynor <ckaynor@zindagigames.com> - 2013-11-26 16:21 -0800

csiph-web