PYTHON blog record 0602, python blog 0602

Source: Internet
Author: User
Tags python list

PYTHON blog record 0602, python blog 0602
The following content is from the unicodestring in MOOC http://www.imooc.com/learn/177 python.

There is another encoding problem in the string.

 

Because the computer can only process numbers, if you want to process text, you must convert the text into numbers before processing. The earliest computer was designed to use eight bits as a byte. Therefore, the maximum integer represented by a word energy saving is 255 (Binary 11111111 = decimal 255 ), 0-255 is used to indicate uppercase and lowercase English letters, numbers, and symbols. This encoding table is called ASCII encoding. For example, the uppercase letter A is encoded as 65 and the lowercase letter z is encoded as 122.

 

To express Chinese characters, it is clear that one byte is not enough. It requires at least two bytes and cannot conflict with ASCII encoding. Therefore, China has developed GB2312 encoding to encode Chinese characters.

 

Similar to other languages such as Japanese and Korean. Unicode came into being to unify the encoding of all texts. Unicode unifies all languages into a set of encodings, so that there will be no garbled issues.

 

Unicode usually represents a character in two bytes. The original English encoding is changed from single-byte to dual-byte. You only need to set the height of all bytes to 0.

 

Because Python was born earlier than the Unicode standard, the earliest Python only supports ASCII encoding, and the common string 'abc' is inside Python.

 

Python later added support for Unicode. The Unicode string is represented by U'... ', for example:

Print u 'Chinese'

In addition to a single u, Unicode strings are no different from common strings. escape characters and Multiline notation are still valid:


 

Print u'chinese \ n Japanese \ n Korean'

Multiple rows:

U''' the second line of the first line '''

Raw + multiple rows:

Ur '''python Unicode strings support "Chinese", "Japanese", "Korean", and other languages '''

 

If the Chinese character string encounters UnicodeDecodeError In the Python environment, this is because the format of the. py file is incorrect. You can add comments in the first line.

# -*- coding: utf-8 -*-

The purpose is to tell the Python interpreter to read source code with UTF-8 encoding. Save it as... with Notepad ++ and save it in UTF-8 format.

 

 

Ii. integers and floating-point numbers in Python

Python allows you to directly perform a four-character hybrid operation on integers and floating-point numbers. The operation rules are exactly the same as those in mathematics.

 

Basic operations:

1 + 2 + 3   # ==> 64 * 5 - 6   # ==> 147.5 / 8 + 2.1   # ==> 3.0375
(1 + 2) * 3    # ==> 9(2.2 + 3.3) / (1.5 * (9 - 0.3))    # ==> 0.42145593869731807


Brackets can be used to increase the priority, which is exactly the same as the mathematical operation. Note that parentheses can only be used, but parentheses can be nested in many layers:

Different from mathematical operations, Python's Integer Operation results are still integers and floating-point calculation results are still floating-point:

1 + 2 #=> integer 31.0 + 2.0 #=> floating point

However, the result of the mixed integer and floating-point operations becomes a floating-point number:

1 + 2.0 #=> floating point number 3.0

Why do we need to distinguish between integer and floating-point operations? This is because the result of integer calculation is always accurate, and the result of floating point calculation is not necessarily accurate, because the computer memory is too large to accurately express the infinite loop decimal, for example, if 0.1 is changed to binary, it means an infinite repeating decimal number.

 

Isn't the result a floating point number when Division operations of integers encounter division?

11 / 4    # ==> 2


Many beginners are surprised that, even if the division of integers in Python is different, the result is still an integer, and the remainder is directly thrown away. However, Python provides a remainder calculation % to calculate the remainder:

11 % 4    # ==> 3

If we want to calculate the exact result of 11/4, we can convert one of the two numbers into a floating-point number by following the "integer and floating-point mixed operation result is a floating-point number" rule:

11.0 / 4    # ==> 2.75
Iii. boolean type in Python

 

# True and True #==> TrueTrue and False #==> FalseFalse and True #==> FalseFalse and False #==> False # or True #==> TrueTrue or False #==> TrueFalse or True #==> TrueFalse or False #==> False # non-operation not True #==> Falsenot False #==> Truea = Trueprint a and 'a = t' or 'a = f' # The calculation result is not boolean, it is the string 'a = t'. Why? # Because Python regards 0, Null String '', and None as False, and other values and non-null strings as True, so: true and 'a = t' # The calculation result is 'a = t' # continue to calculate 'a = t' or 'a = f'

To explain the above results, it involves an important rule for the and or operations: short circuit calculation.

1. when calculating a and B, if a is False, then according to the calculation rule, the entire result must be False, so a is returned; if a is True, the entire calculation result depends on B, so B is returned.

 

2. when calculating a or B, if a is True, then according to the or algorithm, the entire calculation result must be True, so a is returned; if a is False, then the entire calculation result depends on B, so B is returned.

 

Therefore, when the Python interpreter performs a Boolean operation, as long as the calculation result can be determined in advance, it will not calculate the result and return the result directly.

 

 

 

 

 

 

4. Create a list using Python

A built-in data type in Python is list: list. List is an ordered set that allows you to add and delete elements at any time.

 

For example, you can use a list to list the names of all the students in the class:

>>> ['Michael', 'Bob', 'Tracy']['Michael', 'Bob', 'Tracy']

List is an ordered set in the mathematical sense. That is to say, the elements in list are arranged in order.

 

It is very easy to construct a list. According to the code above, all the elements of the list are directly included in [], which is a list object. In general, we assign the list value to a variable, so that we can reference the list through the variable:

Classmates = ['Michael ', 'Bob', 'tracy '] classmates # print the content of the classmates variable >>> ['Michael', 'bob', 'tracy ']

Since Python is a dynamic language, the elements contained in the list do not need to be of the same data type. We can include various types of data in the list:

L = ['Michael', 100, True]

A list that does not have an element is an empty list:

empty_list = []
# Print sequence table L = ['Adam ', 95.5, 'lisa', 85, 'bart', 59] print L

 

V. Accessing the list by index in Python


Because list is an ordered set, we can use a list to show three students in the course from high to low by score:

L = ['Adam', 'Lisa', 'Bart']

Then, how can we obtain the specified nth name from the list? The method is to obtain the specified Element in the list through the index.

 

Note that the index starts from 0, that is, the index of the first element is 0, the index of the second element is 1, and so on.

 

Therefore, to print the name of the first student, use L [0]:

However, when using indexes, do not cross-border, so there is no L [3].

Vi. access list in reverse order of Python
L = ['Adam', 'Lisa', 'Bart']print L[-1]>>>Bart
 
7. Add new elements to the Python list
L = ['Adam', 'Lisa', 'Bart']

 

Add new student Paul to the existing list

7.1 append ()

The first method is to append new students to the end of the list using the list append () method:

L = ['Adam', 'Lisa', 'Bart']L.append('Paul')print L>>> ['Adam', 'Lisa', 'Bart', 'Paul']

Append () always adds new elements to the end of the list.

 

7.2 insert ()

Using the insert () method of list, it accepts two parameters. The first parameter is the index number, and the second parameter is the new element to be added:

L = ['Adam', 'Lisa', 'Bart']L.insert(0, 'Paul')print L>>>['Paul', 'Adam', 'Lisa', 'Bart']

L. insert (0, 'Paul ') means that 'Paul' will be added to the position where the index is 0 (that is, the first one ), adam, whose original index is 0, and all later students, are automatically moved one by one.

 

8. Delete elements from the list using Python
 L = ['Adam', 'Lisa', 'Bart', 'Paul']L.pop()>>>'Paul' print L>>>['Adam', 'Lisa', 'Bart']

Pop () deletes the last one by default.

L = ['Adam', 'Lisa', 'Paul', 'Bart']L.pop(2)>>>'Paul'print L>>> ['Adam', 'Lisa', 'Bart']

9. Replacing elements in the Python List
L = ['Adam ', 'lisa', 'Paul ', 'bart'] L [2] = 'polo' # Or L [-1] = 'polo' print L> L = ['Adam ', 'lisa ', 'Paul ']
10. Create tuple in Python

Tuple is another ordered list, which is translated into "tuples" in Chinese ". Tuple and list are very similar. However, once a tuple is created, it cannot be modified.

 

It also indicates the name of the class member, and tuple indicates the following:

t = ('Adam', 'Lisa', 'Bart')

  

The only difference between creating a tuple and creating a list is that [] is replaced by ().

 

Now, this t cannot be changed. tuple does not have the append () method or the insert () and pop () methods. Therefore, new students cannot directly add data to tuple, and old students cannot quit tuple.

 

The method for retrieving tuple elements is the same as that for listing elements. We can normally use t [0], t [-1] and other indexing methods to access elements, but cannot assign values to other elements.

 

11. Create a single-element tuple in Python

Like list, tuple can contain 0, 1, and any number of elements.

 

Tuple that contains multiple elements. We have already created a tuple.

 

A tuple that contains 0 elements, that is, an empty tuple, which is directly represented:

t = ()print t>>>()

  

T = (1) print t >>> 1 #??? This is why, because () can represent both tuple and the priority of the operation as parentheses. Result (1) is calculated by the Python interpreter. Result 1, the result is not a tuple, but an integer of 1.

  

It is precisely because the tuple defining a single element with () is ambiguous. Therefore, Python requires that a comma "," be added to the single element tuple to avoid ambiguity:

t = (1,)print t>>>(1,)

When printing a single-element tuple, Python also automatically adds a "," to clearly tell you that this is a tuple.

 

The effect of adding this extra "," to the Multi-Element tuple is the same.

 

 


12. Variable tuple in Python

 

T = ('A', 'B', ['A', 'B']) # t = ('A', 'B', ('A ', 'B') is immutable.

Note that t has three elements: 'A', 'B', and a list: ['A', 'B']. As a whole, list is the 3rd elements of tuple. The list object can be obtained through t [2:

 L = t[2]L[0] = 'X'L[1] = 'Y'print t>>>('a', 'b', ['X', 'Y'])

 

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.