On Tue, Nov 26, 2013 at 4:01 PM, Victor Hooi <victorh...@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".
-- https://mail.python.org/mailman/listinfo/python-list