How do I format a string using a dictionary in Python 3?

PythonServer Side ProgrammingProgramming

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

raja
Published on 18-Dec-2017 16:11:53
Advertisements