| by Arround The Web | No comments

Python String format_map() Method

While working with strings in Python, we sometimes need to add multiple values inside the strings (substituting values). To substitute the multiple values while string formatting the “string.format_map()” method is used in Python. This method is similar to the “format()” method but more efficient and faster. Unlike the “format()” method, we directly pass the mapping dictionary to the “string.format_map()” method.

The following contents provide you with a comprehensive tutorial on the Python “string.format_map()” method:

What is the Python “string.format_map()” Method?

Conclusion

What is the Python “string.format_map()” Method?

The “string.format()” method is similar to the “string.format()” method with slight differences. It is used to format the specified values in each string using a dictionary.

Syntax

string.format_map(z)

 
Parameters

In the above syntax:

    • The “string” here specifies the original string that is used to format the string.
    • The “z” specifies a mapping dictionary. It contains the value to be substituted for the placeholder in the string.

Return Value

The “string.format_map()” method retrieves the new string with the specified values formatted according to the placeholders in the original string. However, the original string remains unchanged.

To get a better know-how let’s perform some examples using the Python string.format_map() method:

Example 1: Working of “string.format_map()” Method

Take this simple case scenario. Here, first, we initialized the dictionary that contains the value to be substituted. Next, we applied the “format_map()” on the specified string by taking the dictionary as an argument.

dict1 = {'x':'Joseph', 'y': 22}
print("{x} is {y} years old.".format_map(dict1))

 
The string has been formatted successfully:


Example 2: Using Multiple Key Values of Mapping Dictionary

Now, we make things more advanced by creating a mapping dictionary with key values as a list. The list contains multiple values placed at specified index positions. Next, the “string.format_map()” method is called on the specified list with placeholder and index value. For example, name[0] and age[0] access the value placed at index position “0” of their respective list.

dict1 = { 'name':['Joseph', 'Anna'], 'age':[20, 21]}
print('{name[0]} is {age[0]} years old.'.format_map(dict1))
print('{name[1]} is {age[1]} years old.'.format_map(dict1))

 
The above code retrieved this:


Example 3: Python “string.format_map()” Method With Custom Function

To increase the functionality, we use the “string.format_map()” method with a custom function. For example, the following code creates the function named “func1” and initializes a mapping dictionary. Next, the “string.format_map()” method formats the string with the mapping dictionary value. In the end, the function takes the specified parameter value which is used as the dictionary key value.

def func1(n):
    dict1 = {'name':"Joseph", 'noti':n}  
    print('{name} has {noti} new notifications'.format_map(dict1))
func1(5)

 
The new string retrieved after the formation of the string:


Example 4: “string.format_map()” Method Working With dict Subclass

In the below code, the “string.format_map()” method is used with a dictionary subclass that overrides the “__missing__()” method. First, we define the dictionary subclass named “func1” that inherits from the “dict” class. The “__missing__()” method retrieves the missing key itself. Next, the string is created with two placeholders. In the last, the “format_map()” method is called on the string by taking the instance value as an argument including the key-value pair. This will substitute the specified value with the string.

class func1(dict):
    def __missing__(self, key):
      return key

str1 = '({x}, {y})'
print(str1.format_map(func1(x='2')))
print(str1.format_map(func1(y='3')))
print(str1.format_map(func1(x='2', y='3')))

 
The above code displays the output:


Example 5: Retrieving KeyError

The “string.format_map()” retrieves a key error when we want to substitute the value to the key that does not exist in the mapping dictionary. Here, in this case, the “{z}” placeholder inside the string retrieves the key error exception.

dict1 = {'x':'Joseph', 'y': 22}
print("{x} is {y} years {z} old.".format_map(dict1))

 
The above code displays this:


Example 6: format_map() and format() Methods

The “format()” method takes the substitution value as an argument and creates the mapping dictionary first before formatting the string. On the other hand, the “format_map()” method performs the string formatting by accepting the mapping dictionary as an argument. The “format_map()” method is faster than the format() method due to this reason. We can also use the dictionary subclass for mapping using the format_map() method. Take this example for further understanding:

dict1 = {'x':'Joseph', 'y': 22}
# Using format_map() Method
print("{x} is {y} years old.".format_map(dict1))
# Using format() Method
print("{x} is {y} years old.".format(x='Joseph', y=22))

 
The above code displays this to output:

Conclusion

The “string.format_map()” method retrieves the formatted string by mapping the specified dictionary key value with the particular string. We format the multiple string value using the multiple mapping value specified as the dictionary key in the form of a list. This guide presented several examples including the difference between the “format()” method and the “string.format_map()” method.

Share Button

Source: linuxhint.com

Leave a Reply