程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python · learning

編輯:Python

object

python Everything is an object , Each object consists of : identification (identity), type (type),value( value ) form

       1. Identification is used to uniquely identify the object ,  Usually corresponds to the address of the object in computer memory , Use built-in functions id(obj) Returnable object obj The logo of ( Is the address in the memory block )

       2. Type is used to represent the storage of objects “ data ” The type of , Types can limit the value range of objects and the operations that can be performed . have access to type(obj) Get the type of object .

       3. Value represents the information of the data stored by the object , Use print(obj) You can print out the value directly .

The essence of an object is : A memory block , Has its specific value , Support specific types of related operations .

quote

stay python in , Variables are also called references to objects , because , Variables store the address of the object , The variable refers to... By address “ object ”.

The variable is located in : Stack memory

The object is located in : Heap memory

python Is a dynamically typed language

Variables do not need to display declaration types , Objects referenced by variables ,python The interpreter automatically determines the data type .

python It's a strongly typed language

Every object has a data type , Only operations of this type are supported .

identifier

identifier : For variables , function , class , Name of module, etc . Identifiers have the following specific rules :

1. Case sensitive , Such as :sxt and SXT Is different

2. The first character must be a letter , Underline , The following characters can be letters , Numbers , Underline

3. Cannot use keyword , such as :if,or,while etc.

4. Names that begin and end with double underscores usually have special meanings , Try to avoid this kind of writing , such as __init__ Is the constructor of a class .

Declaration and assignment of variables

The declaration and assignment of variables are used to bind a variable to an object , The format is as follows :

Variable name    =    expression

Delete variables and garbage collection mechanism

Can pass del Statement to delete variables that are no longer used , example :del a

If a variable has no variable reference , It will be recycled by the garbage collector , Clear memory space .

  Chained assignment

Chained assignment is used to assign the same object to multiple variables

x=y=123    amount to :x=123;y=123

Series unpacking assignment

A series of data is assigned to variables corresponding to the same number ( The number must be consistent )

a,b,c  = 4,5,6    amount to :a = 4;b = 5;c = 6

Variable exchange can be realized by using series unpacking assignment

Constant

python Constants are not supported , There are no syntax rules that restrict changing the value of a constant . You can only agree that constants do not change

Introduction to the most basic built-in data types

 1. Integers   2. floating-point    3. Boolean type    4. String type

Numbers  

 

  Integers

 python in , except 10 Base number , There are three other bases :

            0b or 0B  Binary system

            0o or 0O octal

            0x or 0X Hexadecimal

These three bases can be carried out very conveniently “ An operation ' operation .

  Use int() Implement type conversion :

1. Floating point numbers are rounded off directly , Such as :int(9.9) The result is :9

2. Boolean value true To 1,false To 0, Such as :int(true) The result is 1

3. The string conforms to integer format ( Floating point number format does not work ) Then it is directly converted to the corresponding integer , Otherwise, the report will be wrong

Automatic transformation :

When integer and floating point numbers are mixed , The expression result is automatically transformed into a floating point number , such as :2+8.0 The result is 10.0

Floating point numbers  

Floating point numbers , be called float. Floating point numbers are represented by scientific counting

Type conversion and rounding  

1. similar int(), You can also use float() Convert other types to floating point numbers

2. When integer and floating point numbers are mixed , The expression result is automatically transformed into a floating point number

3.round(value) You can return a rounded value ( But it won't change the original value , Instead, new values are generated )

  Comparison operator

  Logical operators

The same operator  

  character string

Basic characteristics of string

The essence of strings is : Character sequence ,python The string of is immutable , We cannot make any changes to the original string . however , You can copy part of the string to the newly created string , achieve ” It seems to be modified ' The effect of .

python Single character type... Is not supported , A single character is also used as a string .

String encoding

python3 Direct support for Unicode, A character that can represent any written language in the world .python3 The default character is 16 position Unicode code ,ASCII Code is Unicode Coded subset .

            Use built-in functions ord() You can convert characters into corresponding Unicode code ;

            Use built-in functions chr() You can convert decimal numbers into corresponding characters .

Quotation marks create strings  

1. You can use single or double quotation marks to create a string . for example :a = ‘abc’;b = ‘’xuexi‘’

The advantage of using these two kinds of quotation marks is that you can create strings that contain quotation marks themselves , Instead of using escape characters .( Single clip double , Double clip sheet )

2. Three consecutive single quotes or three double quotes , You can create multiline strings .

  Empty string and len() function

python Allow the existence of empty strings , Does not contain any characters and has a length of 0.

len() Used to calculate how many characters a string contains .

Escape character

Use “\+ Special characters ", Achieve some effects that are difficult to express with characters .

String splicing

  have access to + Concatenate multiple characters .

a. if + Both sides are strings , Then splicing .

b. if + There are numbers on both sides , Then add .

c. if + There are different types on both sides , Throw an exception .

Multiple literal strings can be put directly together to realize splicing .

  String copy

Use * You can copy strings

Print without wrapping

  call print when , Will automatically print a line break . When you don't want to wrap lines , You can use parameters end = ” Any string “. Add anything at the end of the implementation .

Read the string from the console

  Use input() Read the string from the console

 str() Realize digital transformation string

 str() Transform other data types into strings

Use [ ] Extract characters

The essence of string is character sequence , We can add... After the string [ ], stay [ ] Specify the offset , You can extract a single character at that position .

        Forward search :

                The first character on the far left , The offset is 0, The second offset is 1, And so on . until len(str)-1 until .

        Reverse search :

              The first character on the far right , The offset is -1, The penultimate offset is -2, And so on , until -len(str) until .

              

 replace() Implement string substitution

Strings are immutable . adopt [ ]  You can get the character at the specified position of the string , But you can't change the string , Otherwise, the report will be wrong .

The string cannot be changed . however , Sometimes certain characters have to be replaced . This can only be achieved by creating a new string .

replace( ) In the process of replacing a string . You actually create a new string object , And points to the variable a, Instead of modifying the previous string , The memory diagram is as follows :

String slice slice operation  

section slice Operation can quickly extract substrings . The standard format is :

 [ Starting offset  start: End offset end: step  step]  Left closed right away

[  :] Extract the entire string

String to achieve reverse output : 

  Put all of... In the string a Character output :

split() Divide and join() Merge

split() You can split a string into multiple substrings based on the specified separator ( Store in list ), If you do not specify a separator , White space characters are used by default ( A newline / Space / tabs ).

join() Function and split() The opposite is true , Used to concatenate a series of substrings .

Splicing string points :

        Use String mosaics +, A new string object will be generated , Therefore, it is not recommended + To concatenate strings . Recommended join function , because join The function calculates the length of all strings before splicing them , Then copy them one by one , Create a new object only once . 

Testing two types of splices takes time :

import time
time01 = time.time() # Start time
a = ""
for i in range(100000):
a += "study"
time02 = time.time() # End time
print(" Operation time :"+str(time02-time01))
time03 = time.time() # Start time
li = []
for i in range(100000):
li.append("study")
a = "".join(li) # Use join Connection string
time04 = time.time() # End time
print(" Operation time :"+str(time04-time03))

String resident mechanism and string comparison

String resident : The method of saving only one copy of the same and immutable string , Different values are stored in the string resident pool .python Support string resident mechanism , For strings that meet the identification rules ( Contains only underscores (_), Letters and numbers ) The string persistence mechanism is enabled .

String formatting

format() Basic usage

format Function can take any number of arguments , Positions can be out of order .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved