
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- How do I serialize a Python dictionary into a string, and then back to a dictionary?
- How do I assign a dictionary value to a variable in Python?
- How do I get an ISO 8601 date in string format 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 modify a string in place in Python?
- How do I execute a string containing Python code in Python?
- How do I convert a string to a number in Python?
- How do I convert a number to a string 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 Input a String From the User in Python?
- How do you Loop Through a Dictionary in Python?
- How to convert the string representation of a dictionary to a dictionary in python?

Advertisements