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


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

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

Started byVictor Hooi <victorhooi@gmail.com>
First post2013-11-26 16:01 -0800
Last post2013-11-26 16:21 -0800
Articles 4 — 4 participants

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


Contents

  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

#60554 — Python String Formatting - passing both a dict and string to .format()

FromVictor Hooi <victorhooi@gmail.com>
Date2013-11-26 16:01 -0800
SubjectPython String Formatting - passing both a dict and string to .format()
Message-ID<fc656c78-a32b-4f85-8da6-a5c7abf1edfa@googlegroups.com>
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
    
I also tried with:

    '{0['cat']} {1} {0['dog']}'.format(my_dict, foo)
    ...
    SyntaxError: invalid syntax

However, I found that if I take out the single quotes around the keys it then works:

    '{0[cat]} {1} {0[dog]}'.format(my_dict, foo)
    "ernie lorem ipsum spot"

I'm curious - why does this work? Why don't the dictionary keys need quotes around them, like when you normally access a dict's elements?

Also, is this the best practice to pass both a dict and string to .format()? Or is there another way that avoids needing to use positional indices? ({0}, {1} etc.)

Cheers,
Victor

[toc] | [next] | [standalone]


#60556

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-11-27 00:14 +0000
Message-ID<52953971$0$29993$c3e8da3$5496439d@news.astraweb.com>
In reply to#60554
On Tue, 26 Nov 2013 16:01:48 -0800, Victor Hooi wrote:

>     '{0['cat']} {1} {0['dog']}'.format(my_dict, foo) ...
>     SyntaxError: invalid syntax

It's a syntax error because you are using the same quotes. You have:

    '{0['cat']} {1} {0['dog']}'


which is parsed as:

STR '{0['
NAME cat
STR ']} {1} {0['
NAME dog
STR ']}'

which isn't legal. You can't write:

    "foo"len

either.

As for why you don't need to quote the keys inside the string format min-
language, that is how the mini-language is designed, and it is for 
convenience and to avoid the sort of trouble you're having now.


> Also, is this the best practice to pass both a dict and string to
> .format()? Or is there another way that avoids needing to use positional
> indices? ({0}, {1} etc.)

I'd do it like this:

py> mydict = {'cat': 42, 'dog': 23, 'parrot': 99}
py> '{cat} and {dog}, {}'.format('aardvark', **mydict)
'42 and 23, aardvark'



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#60558

FromMichael Torrie <torriem@gmail.com>
Date2013-11-26 17:21 -0700
Message-ID<mailman.3265.1385511711.18130.python-list@python.org>
In reply to#60554
On 11/26/2013 05:01 PM, Victor Hooi 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

This is a syntax error because of the way that the ** unpacks the
dictionary.  For this not to be a syntax error, foo has to be before
my_dict.  This is because in parameter passing, keyword args are always
passed last.  In general I don't think you want to unpack the dictionary
in this case.

> I also tried with:
> 
> '{0['cat']} {1} {0['dog']}'.format(my_dict, foo) ... SyntaxError:
> invalid syntax

This is a syntax error because the cat and dog are not valid python
keywords.  A string is anything between two delimiters. So your command
looks to python like this:

'{0[' cat ']} {1} {0[' dog ']}'.format(my_dict, foo)

If you have a proper syntax-highlighting editor you'll see right away
that cat and dog are not within the string delimiters.

This would work, however:

"{0['cat']} {1} {0['dog']}".format(my_dict, foo)

> However, I found that if I take out the single quotes around the keys
> it then works:
> 
> '{0[cat]} {1} {0[dog]}'.format(my_dict, foo) "ernie lorem ipsum
> spot"
> 
> I'm curious - why does this work? Why don't the dictionary keys need
> quotes around them, like when you normally access a dict's elements?

I suppose it's because the string formatter simply doesn't require it.

> Also, is this the best practice to pass both a dict and string to
> .format()? Or is there another way that avoids needing to use
> positional indices? ({0}, {1} etc.)

Can't you just list them as separate arguments to format?  Like you did
in your working example?

[toc] | [prev] | [next] | [standalone]


#60559

FromChris Kaynor <ckaynor@zindagigames.com>
Date2013-11-26 16:21 -0800
Message-ID<mailman.3266.1385511717.18130.python-list@python.org>
In reply to#60554

[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".

[toc] | [prev] | [standalone]


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


csiph-web