In a scripting language like Python, a lot of processing is performed to insert an arbitrary character string only partly in a standard sentence. When printing a New Year's card, there are times when only the name in the message is changed and printed, but what is merge processing? Point to. Python provides a format () method for easy merge processing. In the format () method, use the string enclosed in curly braces ({}) to specify where to insert the string in the template. If you pass an object to a format string like {0} or {1.attr_a}, it will return the string with the string inserted in the part enclosed in curly braces. If you use the format () method, it is close to the template engine used in web application frameworks etc. You can take advantage of advanced string formatting features. The character string format function that uses the% operator used in Python2 is a function that has been announced to be abolished in the future. It's still available in versions up to Python 3.5, but for the future it's better to use the format () method unless you have a specific reason to do so.
[Insert a character string into the format] “{}” loves Python !”.format(‘Hatamoto’) ↓ Hatamoto loves Prthon !
The part enclosed in double quotation marks is the template character string. Insert the character string given as an argument to the format () method in the part enclosed in curly braces and return the result.
You can write multiple replacements for curly braces. Below is an example of creating a link to a Python related site by combining the format () method, list, and for statement.
[Insert multiple at the same time] linkstr = ‘{}’ for i in [ ‘http://python.org’, ‘http://pypy.org’, ‘http://cython.org’,]: print(linkstr.format(i i.replace(‘http://’, ‘’))) ↓ python.org pypy.org’ cython.org
The URL is specified in the first element, and the character string without "http: //" is specified in the second element. In this way, the appeal of the format () method is that you can easily create a standard character string.
[Specify the insertion position with a numerical value] “{0} {1} {0}”.format(’Spam’, ‘Ham’) ↓ Spam Ham Spam
[Specify the insertion position with the key] “{food1} {food2} {food1}”.format(food1 = ’Spam’, food2 = ‘Ham’) ↓ Spam Ham Spam
[Specify the insertion position in the dictionary] d = {‘name’ : ‘Hatamoto’, ‘birthyear’ :1995} “{0[birthyear]} is {0[name]}’s birthyear.”,format(d) ↓ 1995 is Hatamoto’s birthyear.
Recommended Posts