![]() |
VOOZH | about |
In Python, we can use a dictionary to format strings dynamically by replacing placeholders with corresponding values from the dictionary. For example, consider the string "Hello, my name is {name} and I am {age} years old." and the dictionary {'name': 'Alice', 'age': 25}. The task is to format this string using the dictionary to produce "Hello, my name is Alice and I am 25 years old.". Let's explore several ways to achieve this.
str.format() method allows passing dictionary values as keyword arguments using the ** operator.
Hello, my name is Alice and I am 25 years old.
Explanation:
Let's explore some more ways and see how we can format a string using a dictionary in Python.
Table of Content
str.format_map() method directly formats the string using a dictionary without unpacking it.
Hello, my name is Alice and I am 25 years old.
Explanation:
For simple cases, we can use f-strings in combination with variable unpacking.
Hello, my name is Alice and I am 25 years old.
Explanation:
The string.Template class provides another way to format strings using $ placeholders.
Hello, my name is Alice and I am 25 years old.
Explanation: