Format a String Using a Dictionary in Python 3



You can use dictionaries to interpolate strings. They have a syntax in which you need to provide the key in the parentheses between the % and the conversion character. For example, if you have a float stored in a key 'cost' and want to format it as '$xxxx.xx', then you'll place '$%(cost).2f' at the place you want to display it.

Here is an example of using string formatting in dictionaries to interpolate a string and format a number:

>>>print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.

You can read up more about string formatting and their operators here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

Updated on: 2020-06-13T14:27:51+05:30

689 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements