Python string format map

Функция format_map() в Python

Эта функция была введена в Python 3.2. Его синтаксис:

Давайте посмотрим на несколько примеров функции format_map().

s = 'My name is and I am a ' my_dict = print(s.format_map(my_dict)) print(s.format(**my_dict))
My name is Pankaj and I am a Software Engineer My name is Pankaj and I am a Software Engineer

Что, если отображение содержит больше ключей, чем нам действительно нужно при форматировании?

my_dict = print(s.format_map(my_dict)) print(s.format(**my_dict))
My name is Meghna and I am a Writer My name is Meghna and I am a Writer

Что делать, если в сопоставлении отсутствуют ключи?

my_dict = print(s.format_map(my_dict))

Посмотрим, что получится, если использовать функцию string format().

Сравнение функций format_map() и format()

Функция format_map() очень похожа на функцию format(). Единственная разница в том, что сопоставления используются напрямую, а не копируются в словарь. Это полезно, когда отображение является подклассом dict.

Если вы посмотрите на приведенные выше примеры, поведение функций format() и format_map() совершенно одинаковое. Давайте посмотрим, чем это отличается, когда отображение является подклассом dict.

class MyDict(dict): def __missing__(self, key): return '#Not Found#' s = 'My name is and I am a ' my_dict = MyDict(name='Pankaj') print(my_dict) print(s.format_map(my_dict))

Поэтому, когда ключ отсутствует, вызывается функция __missing__, и вывод используется для замены подстановки.

Посмотрим, что произойдет, если мы попробуем использовать здесь функцию format().

Функция format() выдает ошибку, поскольку копирует предоставленные сопоставления в новый объект dict. Таким образом, подкласс, в котором мы реализовали функцию __missing__, никогда не используется, и, следовательно, возникает ошибка.

Заключение

Функция format_map() полезна, когда мы хотим использовать подкласс dict для целей сопоставления. Поскольку отображение используется напрямую, вызываются функции из подкласса, тогда как, если мы используем функцию format(), сопоставления копируются в новый объект dict, а функции нашего подкласса не будут вызываться.

Источник

Using Python String format_map()

Python String Format Map

In this article, we’ll take a look at thePython String format_map() method.

This method returns a formatted version of the string using a map-based substitution, using curly brackets <>.

Let’s understand this properly, using a few examples.

Basics of Python String format_map()

The Python String format_map() function is available from Python 3.2 onward, so make sure you’re using the updated versions of Python and not the legacy ones.

The basic syntax of this String method is as follows:

substituted_string = str.format_map(mapping)

Here, mapping can be any mapping, like a Dictionary. A mapping can be viewed to be of the form < key : value >.

The Python String format_map() method replaces all keys in the string with the value .

This will return a new string, with all substitutions made, if applicable.

To understand this better, consider a mapping dictionary below:

Now, consider a format string having the keys of the dictionary under the format substitution (curly brackets).

fmt_string = "Hello from . is a site where you can learn "

Now, we can substitute all occurences of with “AskPython” and all occurences of with “Python” using format_map() .

print(fmt_string.format_map(dict_map))
Hello from AskPython. AskPython is a site where you can learn Python

We get our desired output, with all substitutions!

Now, what if we have an extra format which does not exist on the mapping dictionary?

dict_map = fmt_string = "Hello from . is a site where you can learn . What about ?" print(fmt_string.format_map(dict_map))
Traceback (most recent call last): File "", line 1, in print(fmt_string.format_map(dict_map)) KeyError: 'other_lang'

We get a KeyError exception. Since does not belong to the mapping dictionary, the lookup will fail!

A Comparison of Python String format_map() vs format()

As you may recall, the format() method is also very similar, by making suitable substitutions on a format string.

The difference can be summarized below:

  • The format() method indirectly performs a substitution using the parameters of the method, by creating a mapping dictionary first, and then performing the substitution.
  • In the case of Python String format_map(), the substitution is done using a mapping dictionary, directly.
  • Since format_map() also does not make a new dictionary, it is slightly faster than format().
  • format_map() can also use a dictionary subclass for mapping, whereas format() cannot.

To illustrate the last point, let’s create a Class which is a sub-class of dict .

We’ll experiment with both the above methods, and also try to handle any missing keys using the __missing__() dunder method.

class MyClass(dict): def __missing__(self, key): return "#NOT_FOUND#" fmt_string = "Hello from . is a site where you can learn ." my_dict = MyClass(site="AskPython") print(fmt_string.format_map(my_dict))
Hello from AskPython. AskPython is a site where you can learn #NOT_FOUND#.

What’s happening here? Since we have only added on our mapping dictionary, the key is missing.

Therefore, “#NOT_FOUND#” is returned by the __missing__() method.

Traceback (most recent call last): File "", line 1, in fmt_string.format(my_dict) KeyError: 'site'

Well, format() does not handle this for us, and it simply raises a KeyError exception. This is because it copies the mapping to a new dictionary object.

Because the mapping is on a new dictionary object (not using our subclass), it does not have the __missing__ method! Therfore, it can only give a KeyError!

Conclusion

In this article, we learned about how we could use the Python String format_map() method to perform substitutions on a format string. We also saw a quick comparison with the format() method.

References

Источник

How To Use Python String Format_Map Method [Python Easy Guide]

python string format_map

In this tutorial, we’ll learn what Python string format_map() method is and how to properly use it. We’ll go through multiple Python code examples to understand how format_map method works.

Introduction: Python String format_map() Method

This method is used to format the string and returns it.

Syntax of format_map() Method

string.format_map( mapping(dictionary) )
  • Python string format_map method takes a single argument( mapping(dictionary) ).
  • It returns a string after formatting it.

Example 1: format_map() works with Dictionary

Output

345 Green Python Programming 345 Python Programming Green 345 Python Programming 345 345Python ProgrammingGreen 345 Green Green 345+Green 345+Green+Python Programming KeyError: 'c'

This is how Python string format_map method works. You can try it with even more examples to better understand the working of this method.

Click here if you want to learn more about this method.

Example 2: Python String format_map() Method Return Value

Output

Python Programming 345 Green

We can see that Python string format map method returns a string after formatting it.

Conclusion

To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string format_map method. I’d be very happy to receive your feedback on this post. Thank you for reading it.

Источник

Читайте также:  Python imaging ubuntu install
Оцените статью