

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I 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
- Related Questions & Answers
- How do I serialize a Python dictionary into a string, and then back to a dictionary?
- How do I serialize a Python dictionary into a string and vice versa?
- How do I assign a dictionary value to a variable in Python?
- How do I display the content of a JavaScript object in a string format?
- How do I do a case insensitive string comparison in Python?
- How do I wrap a string in a file in Python?
- How do I get an ISO 8601 date in string format in Python?
- How do I execute a string containing Python code in Python?
- How to convert a String representation of a Dictionary to a dictionary in Python?
- How do I un-escape a backslash-escaped string in Python?
- How do I create a random alpha-numeric string using C++?
- How do I format the axis number format to thousands with a comma in Matplotlib?
- How do I sort a list of dictionaries by values of the dictionary in Python?
- How to convert the string representation of a dictionary to a dictionary in python?
- How do I check whether a file exists using Python?
Advertisements