Python String Formatting - passing both a dict and string to .format()
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Nov 26 19:14:41 EST 2013
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
More information about the Python-list
mailing list