concat string and dict in print statement

Peter Otten __peter__ at web.de
Fri Dec 5 13:11:21 EST 2014


gaurangnshah at gmail.com wrote:

> I am trying to combine string and dict in the print statement, however
> getting an error. Would someone let me know what will be correct way to do
> that.
> 
> stats={'lname': 'shah', 'fname': 'gaurang'}
> a=test
> 
> print "%s %(fname)s %(lname)s" %(a,stats)
> 
> Following is the error I am getting
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: format requires a mapping

Try the str.format() method:

>>> stats = {'lname': 'shah', 'fname': 'gaurang'}
>>> a = "test"
>>> print "{0} {1[fname]} {1[lname]}".format(a, stats)
test gaurang shah





More information about the Python-list mailing list