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? -- https://mail.python.org/mailman/listinfo/python-list