From formatting expressions to methods, learn Python

Source: Internet
Author: User

From formatting expressions to methods, learn Python

Now let's take a detailed description of the formatting method.

Basic operations

The so-called formatting method is to first create a template for the output string, and then use format to fill the template content.

Copy codeThe Code is as follows:
>>># Create a string template first
>>> Template = "My name is {0}. My website is {1}. I am writing {2 }."

>>># Use format to correspond to the serial number content in the template in sequence
>>> Template. format ("qiwsir", "qiwsir. github. io", "python ")
'My name is qiwsir. My website is qiwsir. github. io. I am writing python .'

Of course, if you want to do this, you can also:

Copy codeThe Code is as follows:
>>> "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 .'

There is no big difference between these expressions and expressions written in %. But don't worry about the official website. Generally, there is no difference between children. When you grow up, there is a difference. Take a look and experiment.

In addition to filling the positions in the template in the corresponding order (like placeholders), you can also use keywords to specify the content of the expected field.

Copy codeThe Code is as follows:
>>> 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 are also acceptable. In addition, the keyword and the previous position number can also be mixed. For example:

Copy codeThe Code is as follows:
>>> "{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 a little interesting? After reading the output result, you will know that the format method is a new str.

Offset of the sequence object

There is a requirement that the first and third letters of a word are displayed in the output. For example, if python is the word, you must tell the viewer that the first letter is p and the third letter is t.

This problem is not difficult. There are also many implementation methods. Here we mainly want to show the application of offset in format.

Copy codeThe Code is as follows:
>>> Template = "First = {0 [0]}, Third = {0 [2]}"
>>> Template. format (word)
'First = p, Third = t'

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

Copy codeThe Code is as follows:
>>> 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'

Here, we will look at an experiment that is a little wordy:

Copy codeThe Code is as follows:
>>> 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") # offset of the specified keyword Value
"Qiwsir's first is q"

It is worth noting that the offset is in the data of the sequence type, because it can be a negative number, that is, it can be counted from the right.

Copy codeThe Code is as follows:
>>> Word
'Python'
>>> Word [-1]
'N'
>>> Word [-2]
'O'

However, the offset of a negative number cannot be used in the template.

Copy codeThe Code is as follows:
>>> "First = {0 [0]}, End = {0 [-1]}". format (word) # 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) # Change-1 to 5.
'First = p, End = N'

Of course, it is completely feasible to put it out of the template. In this way:

Copy codeThe Code is as follows:
>>> "First = {0}, End = {1}". format (word [0], word [-1])
'First = p, End = N'

Dictionary key

Go directly to the experiment, observe first, and draw a conclusion.

Copy codeThe Code is as follows:
>>> 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 100'

The value corresponding to the dictionary key in the format parameter is obtained. It's too long. Let's see the example. Obtained by location, and can also be obtained by Keyword:

Copy codeThe Code is as follows:
>>> Myinfo
{'Website': 'qiwsir. github. io ', 'name': 'qiwsir', 'room': 703}
>>> "My website is {info [website]}, and I like {0}". format ("python", info = myinfo) # The keyword info references a dictionary.
'My website is qiwsir. github. io, and I like python'

Add attributes to the template

I don't know what the title is. Let's look at the experiment.

Copy codeThe Code is as follows:
>>> Import math
>>> "PI is {PI. pi}". format (PI = math)
'Pi is 3.14159265359'

This is a keyword. The following is a slightly more complex point, and the location is used.

Copy codeThe Code is as follows:
>>> Import sys, math
>>> 'Pi is {0.pi}. My lptop runs {1. platform} '. format (math, sys)
'Pi is 3.14159265359. My lptop runs linux2'

You can understand it.

Other hexadecimal

In this field of mathematics in the world, apart from the commonly used decimal and twelve decimal places (what time is it? This is what you often use, and the clock surface is in 12 hexadecimal format) there are other hexadecimal formats, such as binary, octal, and hexadecimal. We will not discuss the hexadecimal issue here. If you are interested in more details, please google them. However, hexadecimal is indeed very important on computers. Because machines use binary at the bottom layer.

Here is just a description of the hexadecimal problem during the output.

>>> "{0: X },{ 1: o },{ 2: B}". format (255,255,255)
'Ff, 377,111 11111'
X: hexadecimal, Hex
O: octal, octal
B: binary, binary
By the way, the output of the formatting method of numbers is the same as that of the formatting expression.

In the formatting method, you can also specify the character width, left and right alignment, and other simple typographical formats. However, in my experience, these seem to be not much used. If you need it, You can google or go to the official documentation.

Some people compare the formatting expressions and formatting methods. Some people say that this is used, and some prefer that. My advice is to use whatever you use. Do not look at the door. However, it is said that the formatting expression may be abolished in a future version. That is what will happen in the future. Now, you can use it easily.


Python and return use the % operator to format the output string

Return is the expression used to return the function value to call the function value.
If you do not use return to call g (a), the code is a statement rather than an expression. That is, g (x) in the Code does not represent any value.
For example, if "> g (1)" and g (a) has return 2, 2 is returned.

2:
A %. 1f floating point number accuracy 1 bit
B %. 2e real number (Science and Technology Development) Accuracy 2 bits
C % 04d integer 4-digit complement with 0
D % d integer

Python formatting and output help

Def bibformat_mla (author, title, city, publisher, year ):
Return '% s. % s. % s: % s, % s "% (author, title, city, publisher, year)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.