A nice way to populate a string with values is to use a dictionary, which can be defined outside of the print statement.
The standard way is to write
>>> print "The temperature in %s is %f degrees" % ('celsius', 20) "The temperature in celsius is 20 degrees" |
Another way using dictionaries is as follows:
>>> data = {'unit': 'celsius', 'value':20} >>> print "The temperature in %(unit)s is %(value)f degrees" % data "The temperature in celsius is 20 degrees" |
This is very convenient when you want to rephrase a sentence without changing the data structure:
>>> print "The temperature is %(value)f degrees (%(unit)s)." % data "The temperature is 20 degrees (celsius)." |
Please follow and like us:
One Response to Python: string substitution using dictionaries