This article is participating in Python Theme Month. See the link for details

My friends, for reprint please indicate the source:…

Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python related questions, so in order to let students master more extended knowledge and better understand AI technology, I asked my assistant to share this Python series of tutorials, hoping to help you! Since this Python tutorial is not written by me, it is not as funny and boring as my AI teaching. But its knowledge points or say in place, also worth reading! PS: if you don’t understand this article, please read the previous article first. Step by step, you won’t feel difficult to learn a little every day!

String formatting also allows the left conversion target to reference the right dictionary key to extract the corresponding value:

>>> "% (n) d % (x) s" % {"n":1,"x":"spam"} '1 spam'Copy the code

In the above example, (n) and (x) in the format string refer to the keys in the right-hand dictionary and extract their corresponding values. Programs that produce something like HTML or XML often take advantage of this technique. You can create a dictionary of values and replace them all at once with a formatted expression based on key references:

>>> reply = """ # Template with substitution targets Greetings... Hello % (name) s! Your age squared is % (age) s "" >>> values = {'name': 'Bob','age': 40} # Build up values to substitute >>> print (reply % values) # Perform substitutions Greetings Hello Bob! Your age squared is 40Copy the code

This trick is also often used with the built-in vars function:

> > > food = 'spam' > > > age 40 = > > > vars () {' food ':' spam ', 'age: 40,... many more... }Copy the code

When the dictionary is used to the right of a formatting operation, it makes the formatting string access the variable by its name (that is, by the keys in the dictionary) :

>>> "% (age) d % (food) s" % vars () '40 spam'Copy the code