Summary of formatting output usage in python and python usage
This example summarizes the format output usage in python. We will share this with you for your reference. The details are as follows:
Python has two types of formatting output syntax.
One method is similar to the C language printf, called Formatting Expression
>>> '%s %d-%d' % ('hello', 7, 1)'hello 7-1'
Another Method is similar to C #, called String Formatting Method CILS.
>>> '{0} {1}:{2}'.format('hello', '1', '7')'hello 1:7'
The first method can specify the floating point precision, for example
>>> '%.3f' % 1.234567869'1.235'
Specify the floating point Precision dynamically during runtime
But how can I dynamically specify the floating point precision through parameters when the code is running?
The magic of python is that it provides a very convenient syntax. You only need to add a * Before typecode (here is f), and the precision of the floating point is specified by the number before it.
>>> for i in range(5):... '%.*f' % (i, 1.234234234234234)...'1''1.2''1.23''1.234''1.2342'
The output results show that the precision is dynamically specified during running, saving the concatenation of formatted strings.
You can use String Formatting Method CILS to complete functions more concisely.
>>> for i in range(5):... '{0:.{1}f}'.format(1 / 3.0, i)...'0''0.3''0.33''0.333''0.3333'
Implement a simple template Tool
The template language provided by Django allows us to bind python variables to the html file through a dict (dictionary). In fact, we can simply Replace the text with the format output of python.
>>> replay = """... Hello World Cup...... Germany vs Brazil... %(germany)d : %(brazil)d""">>> print(replay % {'germany': 7, 'brazil': 1})Hello World Cup...Germany vs Brazil7 : 1
You can also play it like this
>>> germany = 7>>> brazil = 1>>> '%(germany)d : %(brazil)d' % vars()'7 : 1'
Access Object Attributes and dictionary key values in formatted strings
>>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'pc'})'My pc runs linux'>>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'pc'})'My pc runs linux'
Access list elements through subscript (positive integer) in formatted strings
>>> somelist = list('SPAM')>>> 'first={0[0]}, third={0[2]}'.format(somelist)'first=S, third=A'>>> 'first={0}, last={1}'.format(somelist[1], somelist[-1])'first=P, last=M'>>> parts = somelist[0], somelist[-1], somelist[1:-1]>>> 'first={0}, last={1}, middle={2}'.format(*parts)"first=S, last=M, middle=['P', 'A']">>>