Learn Python from formatting expressions to methods

  • 2020-04-02 14:13:17
  • OfStack

Now let's do a little more detail about the formatting method.

Basic operation

The so-called format method, is that you can first set up an output string template, and then use the format to fill the template content.


>>> # Let's make a string template
>>> template = "My name is {0}. My website is {1}. I am writing {2}." >>> # with format Corresponds in turn to the ordinal content in the template
>>> template.format("qiwsir","qiwsir.github.io","python")
'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'

Of course, the above operation is ok if you want to do so:


>>> "My name is {0}. My website is {1}. I am writing {2}.".format("qiwsir","qiwsir.github.io","python")
'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'

These are not very different from expressions written with %. But don't worry, the general children are not distinguish, grew up to have a difference. Take your time and experiment.

In addition to filling in the template in the corresponding order (similar to placeholders), you can also use keywords to indicate the contents of the fields you want.


>>> template = "My name is {name}. My website is {site}"
>>> template.format(site='qiwsir.github.io', name='qiwsir')
'My name is qiwsir. My website is qiwsir.github.io'

The content specified by the keyword is not necessarily STR, other data types can also be. In addition, key words and the previous position number, can also be mixed. Such as:


>>> "{number} is in {all}. {0} are my number.".format("seven",number=7,all=[1,2,3,4,5,6,7,8,9,0])
'7 is in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]. seven are my number.'

Is it starting to feel interesting? Look at the output, you know, after the format method is a new STR.

The offset of the sequence object

There is a requirement to display the first and third letters of a word in the output. The word python, for example, tells the viewer that the first letter is p and the third letter is t.

The problem is not difficult. There are many methods to implement, here is mainly to show the offset in the format application.


>>> template = "First={0[0]}, Third={0[2]}"
>>> template.format(word)
'First=p, Third=t'

List is also of sequence type, and its offset is also acceptable.


>>> word_lst = list(word)
>>> word_lst
['p', 'y', 't', 'h', 'o', 'n']
>>> template
'First={0[0]}, Third={0[2]}'
>>> template.format(word_lst)
'First=p, Third=t'

To summarize the above, a little bit more verbose experiment:


>>> template = "The word is {0}, Its first is {0[0]}. Another word is {1}, Its second is {1[1]}."
>>> template.format("python","learn")
'The word is python, Its first is p. Another word is learn, Its second is e.' >>> "{name}'s first is {name[0]}".format(name="qiwsir")    # Specifies the offset of the value of the keyword
"qiwsir's first is q"

It is important to note that the offset is in the serial-type data, because it can be negative, meaning you can count from the right.


>>> word
'python'
>>> word[-1]
'n'
>>> word[-2]
'o'

However, you cannot use negative offsets in a template.


>>> "First={0[0]}, End={0[-1]}".format(word) # An error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str >>> "First={0[0]}, End={0[5]}".format(word)  # the -1 Instead of 5 That's it.
'First=p, End=n'

Of course, it's perfectly possible to put it outside the template. That's it:


>>> "First={0}, End={1}".format(word[0],word[-1])
'First=p, End=n'

The dictionary keys

Go directly to the experiment, observe first, then get the conclusion


>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> template = "I am {0[name]}"
>>> template.format(myinfo)
'I am qiwsir'
>>> template = "I am {0[name]}. My QQ is {qq}"
>>> template.format(myinfo,qq="26066913")
'I am qiwsir. My QQ is 26066913'

The position followed by the key, you can get the dictionary key corresponding value in the format parameter. Too wordy, just look at the examples. According to the location, but also according to the key words:


>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> "my website is {info[website]}, and I like {0}".format("python",info=myinfo)    # keywords info The reference is to a dictionary
'my website is qiwsir.github.io, and I like python'

Add attributes to the template

You can't read the headline. Look at the experiment.


>>> import math
>>> "PI is {PI.pi}".format(PI=math)
'PI is 3.14159265359'

This is using keywords, let me do it a little more complicated, using position.


>>> import sys,math
>>> 'PI is {0.pi}. My lptop runs {1.platform}'.format(math,sys)
'PI is 3.14159265359. My lptop runs linux2'

You see.

The other base

In this world of mathematics, in addition to the decimal, decimal (what time is it, this is what you and I use, the clock surface is 12), hexadecimal (you are familiar with this), there are other bases, such as binary, octal, hexadecimal, and so on. We won't talk about the base system here. If you are interested in learning more about it, please visit your respective Google. However, bases are really important on computers. Because the machine is binary at the bottom.

This is just to illustrate the base problem when output.

> > > "{0: X}, {1: o}, {2: b}". The format (255255255).
'FF, 377, 11111111'
X: Hex,Hex
O: octal,octal
B: binary,binary
By the way, the format output for Numbers is the same as for formatting expressions.

In formatting, you can also specify simple typographical formats such as character widths and left and right alignment, but in my experience, these don't seem to be used much. If you need to, you can go to Google or go to the official documentation.

Some people make a lot of comparisons about formatting expressions and formatting methods, some say this, some prefer that. My advice is to use whichever one you like. Don't think of it as a school of thought. However, it is rumored that formatting expressions may be abolished in a future version. That's in the future. Let's talk about it in the future. Now, you just take it easy.


Related articles: