Python All-Stack Python Foundation (vi) Pre-Foundation finishing

Source: Internet
Author: User

Computer, there are only CPUs with execute permission, only cpu! can execute instructions

The text or text that people enter on the application is called plaintext!

Characters are entered or printed on the screen, and the computer holds a binary number encoded with a character.

Variable assignment rules: for example: A=1

First in memory to open a space, the number of 1, memory will have a corresponding ID number, and then the variable a point to the memory area and ID number, Python compiler has the function of garbage removal, if the opening of this area of memory is not invoked for some time, the data will be cleared, for other data space.

Python2 High fault tolerance, smart to complete the transcoding splicing.

Python3 the byte type and string type completely clear apart, if the different types of splicing, will error!

#字符编码

ASCII code: 127 digits: 7 bits-----------> United States of America

Extended ASCII code: 256 digits: 8 bits---------> Latin

Chinese extended ASCII (GB2312): Thousands of status----------> China

Chinese extended ASCII (GBK): 20,000 status----------> China

Unicode (Clear text: binary digits): two bytes------------> 60,000 more states-------worldwide

Utf-8 (binary binary):-------Worldwide

Py2. X str:bytes Data unicode:unicode encoded binary data

Py3. x str:unicode (U) bytes:bytes (b) < storage and transfer using >

Knowledge Points:

1, Unicode (2 bytes, universal code), UTF-8 (variable length encoding, English 1 bytes, Chinese 3 bytes), GBK (2 bytes) are encoded.

2. Memory stores binary data in Unicode format (can be understood as a file).

3. The text is saved to the hard disk by encoding the Unicode encoded file in Utf-8. The storage file in utf-8 format is small in space.

Repr (): View byte data

Different forms of coding, there are signs in front (Unicode corresponds to u)

Decode (parameter): parameter: Refers to decoding rules! Decoding

Encode (parameter): parameter: Refers to coding rules! Encoding

Python2 High fault tolerance, smart to complete the transcoding splicing.

Python3 the byte type and string type completely clear apart, if different types of splicing mixed, will be error! The method that can be used in a string is the same as a string or byte data!

IDE compiler execution no problem, but not necessarily the terminal execution is not a problem, you can first execute the test on the IDE, the output of the data into Unicode format, in the terminal test, then one is to determine the terminal is the format of the encoding, the IDE compiler encoding format #coding:* * * * * * * * Represents the coding rules, and then the test is judged on the terminal.

Note the point:

1, UNICODE,UTF-8,GBK are coding rules.

2. Why memory is stored in Unicode.

Any data execution is put into memory first, and encoding and decoding are all done during the execution of the file.

Encoding: PlainText-----------> Binary data

Decoding: Bytes Data---(decoding mode)-----> Binary Data

Object. Method () < object must correspond to the method that can be called! >

#变量

1, cannot begin with the number, the special character, the underline _ can use, in the name.

2. Cannot be named by keyword

Indents and control blocks. If, loop, Function!

Note: #或是三个 "" or "" "" "

#运算符:

Arithmetic operators: +-*/

Assignment operator: = + = = *=/=

Comparison operator: = = (equals) >= <=! = Compares the result, returns a Boolean value! (Must be a Boolean value!) )

Logical operators: and (with) or (or) not (non)

True and False-------> False and False----------> False

Judgment will be one to execute judgment, starting from the first;

And depending on the right in the first symbol, something will be the result of the decision, will follow the decision of the value returned, if the first pair, will be judged later, with the final effect of the return value, or the right in the back of the symbol.

The relational operator in does not belong to the same object, return a Boolean value!

Bitwise operators

#数据类型

integer int has only one expression, called the long Integer type.

Variable data types: list, dictionary

Immutable data types: Integer tuple strings-----------> Once created, cannot be modified

float float (f), Science and Technology Law E represents 10 negative one-time square 0.000123 1.23e-4

Folat double precision is not the same

The Boolean value itself is a data type (True = 1 False = 0), which can be computed.

Process Control

#字符串 (string:)

s= ' let\ ' go ' \ Escape symbol

Native string print (R "\fsjiaakdxie." )

Find: Slice [:]

S1 = "Hello World" print (S1[1:4]) print (S1[1:4:2])

The. Strip ("parameter") removes the spaces at the beginning and end of the string and \ n. The parameter can be any one character structure.

Stitching method

+ Method s= The efficiency of "hello" + "world" depends on the number of stitching files. Two stitching and then go to open the memory space to store the merged data. And so on

Join Method "*". Join (["I", "AM", "world"]) to stitch together strings at intervals of *. The right side is a tabular string, the integral type can not be changed, so not splicing!

Segmentation method

"String". Split ("delimiter", maximum number of splits) s= "Hello World". Split ("") separates the strings with a space separator, resulting in a list. Separated by a separator, the delimiter in the result is not left.

. Rsplit () splits the string from right to left!

. Splitlines () splits the string according to the newline character.

Finding characters find () not found no error

Print ("Hello World". Find ("L")) search from left to right, find one to return index value

Print ("Hello World". RFind ("L")) search from right to left, find one to return index value

Print ("Hello World". Find ("L", 3) looks for a position indexed to 3 from left to right, and returns an index value if one is found.

Print ("Hello World". Index ("L") finds the index value of the corresponding character from left to right, and returns the error if it is not found.

Replace

Print ("Hello World". Replace ("World", "Python")) exactly matches, one-to-a-match, as long as a character match is not on the error.

For the immutable data operation of the string, there will be a return value, and the original string will not change.

Uppercase and lowercase swaps

Print ("Hello World". Swapcase ()) uppercase to lowercase, lowercase to uppercase!

Capitalize first letter

Print ("Hello World". Capitalize ()) string begins with the first letter capitalized!

Title

Print ("Hello World". Title ()) string with the first letter capitalized!

"HEllo World". Upper () whether the string is case-insensitive, all uppercase!

"HEllo World". Lower () whether the string is case-insensitive or not, all of it becomes lowercase!

Position alignment

Print ("Hello World") Center (50, "*") displays Hello World, all text is 50 characters, and other blank positions are filled by *.

Print ("Hello World". Ljust (50, "*")) Align Left

Print ("Hello World". Rjust (50, "*") Align Right

. Zfill () The number of characters, the more out of the complement 0. The string is on the right.

The formatted output of the string. The position of the fill in the format () string and the string that is added behind it are the one by one corresponding relationships.

The dictionary is stored in the. Format_map () brackets.

Print ("Hello%s,%s"% ("SB", "Egon"))

Placeholder

%s string

%d integral type

%f floating Point type

Determine if a string is a number

"A". Isdecimal ()

" -12". IsDigit ()

The IsNumeric () is highly targeted and can be recognized for numbers in Chinese.

Print output, returns a Boolean value.

Occupy space

"Hello\tworld". Expandtabs () default 8 spaces for \ t, if you want to stagger multiple points, enter the number you want to expand in the parentheses behind.

Is the beginning of the judgment function, after the operation of the string will return a Boolean value, is true, the wrong is flase.

A list can iterate over an object: A For loop can be

#创建形式 L = [1, "Hello", [4,5],{"name": "Egon"}]

L2 = List ([]) [] is called a sequence, and the elements to be placed in the list are summed up.

#查: slices [:]

Gets the index value of the list and the corresponding element.

The first method: the use of flag bits

Count=0

For i in [11,22,33]:

Print ("%s---------%s"% (count,i))

Count+=1

The second method:

L = [11,22,33]

For I in L:

Print (L.index (i), i)

Third method: the enumerate () function automatically generates sequence numbers and values

L = [11,22,33]

For i,v in Enumerate (l,1): #函数后可以自定义序号.

Print (I,V)

#增加 This operation has no return value!

L.append () Append, add at the last position, can only add one object at a time!!!

Add multiple elements: L.extend ()

You can add multiple elements, either in the middle, separate, or put a list. L.expend ([7,8])

Specify location Add insert:. Instert (position, Element) Example: L.instert (2, "Zhang")

#删除

Delete by location: L.pop () The last one is deleted by default, and you can specify a location. There is a return value!!! , the returned value is the deleted element.

Delete a specific content: L.remove () put the element you want to delete in parentheses.

Delete the whole, or a section of the list del l[1] del l[] del L[1:3]

#改 assignment operation!!!

The data in the string string is changed by the location of the index value, but the corresponding memory address has not changed l[2][0]=.

Empty l.clear () to empty all the data in the list!!! The list #推荐新建的方式 is not the same as l4=[]. Empty the original list, not a new empty list, high efficiency!

#计算数量. Count () counts the number of an element in the enumeration

[[1,2,3,4].count (3)

Count all of the list: Len print (len (l))

#排序:. Sort () from small to large, no return value! Ord built-in function to view ASCII code!

Sort order can adjust itself, reverse =true (from large to small row) reverse =false (small to large row)

Sorted ([+]) built-in functions, sorted () can also be sorted!

Max () Max min () minimum value

#复制 shallow copy and deep copy

#反转

. Reverse () Reverses the sort directly, regardless of the order of the data in the list.

Tuples are immutable types and data cannot be changed!

#创建

T = (All-in-all) print (t)

t2 = tuple ([]) print (T2)

#不能进行修改操作

#查

Print (t[:]) Prints all

Dictionary

The only data type in Python that has a mapping relationship: The query efficiency of the dictionary is higher than the list

#创建 keys are unique and immutable data types!

d={"name": "Alex", "Age": 23}

#查

Print (d["name"])

V=d.get ("name", None) #推荐

Print (v)

#遍历查询

For loop, take the dictionary key!

For I in D

Print (i, "-------->" d[i]) #对应打印字典里的键值对

Print ("%s------>%s"% (I,d[i]) #格式化打印

You can use list to convert to lists

Print (D.keys ()) #将键全部写入一个列表

Print (D.values ()) #将值全部写入一个列表

Print (D.items ()) #将字典中的键值对, does not constitute a tuple, the overall composition of a list output.

#增

d["Age"]=123

#修改

d["key"] = value d["1"]=666

#删除

Delete D.pop ("1") according to the key has a return value!. Popitem () randomly deletes a

Any data can be deleted by Del

D.clear () empties the dictionary and leaves the empty dictionary.

D.update () #增加字典, if no dictionary is added, there is an overlay.

d2={"height": 123, "sex": "Male",}

D.update (D2)

Print (d)

For I in (Sequence object seq): #seq可以是字符串, list, tuple, dictionary!

Cycle

1. The number of cycles is determined by the number of first-order elements in the sequence!

2, item is defined as a variable range () corresponding to a list, by default from 0, you can customize the starting position.

Continue #结束本次循环

Break #结束整个循环

While loop dead loop!

While conditional expressions or Boolean values:

Execute code

Set set and Dictionary is a set, is no value two functions: 1, go to weight, 2, the relationship test

is a mutable data type! Print ({[+]: "Hello"}) will error!

The elements within the set set must be immutable data types! Print ({1,2,[3,4]}) will error!

s = Set ([1,3, "hello"]) or s2={1,2,3}

Print (S,S2)

#去重:

L = [1,2,2,34,45]

s= "Hello"

Print (Set (L))

Print (set (s)) output result {"H", "E", "L", "O"} Remove Duplicate "L", output one!

#关系测试

S1 = {"Hello",

s2={1,2, ("A", "B")}

linux={"Hello", 4,5,6}

python={"Hello", 3,4,5}

#求并集

Print (s1.union (S2))

Print (S1 | s2)

#求交集 two of them.

Print (s1.intersection (S2))

Print (S1 & S2)

#求差集 I have something I don't have.

Print (s1.difference (S2))

Print (S1-S2)

#对称差集 combine them with none. #把两个互相不在的全打印

Print (s1.symmetric_difference (S2))

Print (S2.symmetric_difference (S1))

Print (S1^S2)

Two collections combine natural to weight! Merge Python into the Linux collection

Linux.update (Python)

Add a new Linux.add ("Alex")

Delete Linux.discard ("Alex") #删除, if the element does not exist, will not error

Linux.remove ("Alex") # Delete, if the element does not exist, will error

Random deletion of Linux.pop () #随机删除

Linux.issubset (python) #子集 determine if it is a subset

Linux.issuperset () #超集, parent set judgment available <,>

Python All-Stack Python Foundation (vi) Pre-Foundation finishing

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.