python basics one
About memory allocation issues
Newly defined string variables open up a new memory space by default
Other similar indexes such as lists, tuples or dictionaries are actually just pointing the variable name to the same address space, as shown below
1 ##The new definition of string opens up a new memory space 2 >>> str1 = 'hoho' 3 >>> str2 = str1 4 >>> id(str1), id(str2) #View the memory object address, observe the memory address, that is, str2 has newly opened up memory space 5 (140297199501752, 140297199501752) #The same thing you see here is caused by an internal mechanism of Python, if the string is large enough It will be different, don't worry 6 >>> str2 = 'heihei' 7 >>> str1 8 'hoho' 9 >>> str210 'heihei'11 >>> ; id (str1), id (str2) (can be understood as a label) points to the same memory address, taking a dictionary as an example, as shown below15 >>> dic1 = {'name':'hoho'}16 >>> dic2 = dic117 >> ;> id(dic1),id(dic2)18 (140297199190088, 140297199190088)19 >>> dic1 = {'name':'hoho'}20 >>> dic2 = dic121 >> > id(dic1),id(dic2) #Check the memory object address and find that it is the same, so modify dic2. In fact, dic1 is also modified 22 (140297199191752, 140297199191752)23 >>> dic2['name' ] = 'heihei'24 >>> dic225 {'name': 'heihei'}26 >>> dic127 {'name': 'heihei'}
List, tuple and dictionary Copy problem (use of shallow copy and deep copy copy module)
1. Lists and tuples can use slices to implement shallow copy, or you can use the copy module to use shallow copy (including dictionary)
2. Use copy.deepcopy( ) Example deep copy
1 >>> import copy 2 >>> list1 = [1,2] 3 >>> list2 = list1 4 >>> list2[0] = 2 #list2 has changed, list1 has changed accordingly 5 >>> list1 6 [2, 2] 7 >>> list3 = list1[:] #Shallow complexity, use array slicing to do shallow copy 8 > ;>> list3 = copy.copy(list1) 9 >>> id(list1),id(list2),id(list3) #Here you can see that the address spaces are different 10 (140297199250696, 140297199250696, 140297199247560)11 >>>
12 >>> list4 = [1,[2]] ##Complex structures must use deep copy 13 >>> list5 = list4[:]14 >>> list515 [1, [2]]16 >>> list5[1][0] = 617 >>> list418 [1, [6]] #You can see it from here In fact, the inner list is not copied, and list4 has also changed accordingly19 >>> list6 = copy.deepcopy(list4) #Deep copy is used here20 >>> list6[1][0] = 821 >>> list622 [1, [8]]23 >>> list424 [1, [6]] #Here you can see what has been copied
Commonly used built-in functions
There are a lot of built-in functions in Python. Just remember the commonly used ones, but you will know how to check which built-in functions there are. The help of the function
Normally, it is divided into three steps
type (variable) ---> Get the variable The class it belongs to
dir (class name) ---> Check what methods are available under the class. Among them, those starting with double underscores like __abs__ generally have alternative methods, such as: __abs__ <=> abs()
help (class name or function name) ---> View the function usage under the class or directly view the function usage
Shaping
1 >>> s,y = divmod(7,3) ## divmod returns data, the value is (quotient, remainder), which can be used for paging 2 >>> s,y3 (2, 1)4 >>> a = -25 >>> abs (-2) #abs takes the absolute value 6 27 >>> len(str(-2)) #takes the speed length 8 2
View Code
Floating point
1 >> > a = 7.02 >>> divmod(a,3)3 (2.0, 1.0)4 >>> a = 7.2355 >>> a.__round__(2) #Round to 6 7.247 > ;>> a.__trunc__() #Round to 8 7
View Code
String
1 >>> str1 = 'this is a string' 2 >>> 'is' in str1 #Member judgment 3 True 4 >>> str1[1:3] # Slicing operation and Index 5 'hi' 6 >>> len(str1) #Length 7 16 8 >>> str1.find('is') ; str1.find('is',3,9)11 512 >>> str1.find('iss') #If not found, return -1. If it is index, an error 13 will be reported -114 >>> str1.index('is',3)15 516 >>> str1.index('iss')17 Traceback (most recent call last):18 File "", line 1, in 19 ValueError: substring not found20 >>> str1 = ' aaa'21 >>> str1.strip() Remove blanks, line feeds, and enter 22 'aaa'23 >>> str1.lstrip()24 'aaa' 25 >>> str1.rstrip()26 ' aaa'27 >>> str1 = 'duiqi' #Alignment operation 28 >>> str1.ljust(20)29 'duiqi ;>> str1.ljust(20,'*')31 'duiqi******************'32 >>> str1.rjust(20,'*' )33 '******************duiqi'34 >>> str1.center(20,'*')35 '************duiqi*** *****'36 >>> str1 = 'this is a string'37 >>> str1.split() ##Split operation 38 ['this', 'is', 'a' , 'string'] 39 > ->'.join([str(i) for i in list1]) #Connection operation 43 '1->2->3'44 >>> str145 'this is a string'46 > >> str1.count('is') #Count 47 248 >>> str1.replace('is','os') #Replace 49 'thos os a string'50 >>> str1.replace('is','os',1) #Replace, only replace one 51 'thos is a string'52 53 str1.startswith('sub') #What starts with 54 str1.endswith('sub' ) #What ends with 55 str1.lower() #Convert to lowercase 56 str1.upper() #Convert to uppercase
View Code
List and tuple (tuple cannot be modified)
1 > >> lst1 = ['a'] 2 >>> lst1.append('b') #Add 3 >>> lst1 4 ['a', 'b'] 5 > >> lst2 = ['c','d'] 6 >>> lst1.extend(lst2) #Extend new 7 >>> lst1 8 ['a', 'b', 'c', 'd'] 9 >>> lst1.insert(0,'z') #insert10 >>> lst111 ['z', 'a', 'b', 'c ', 'd']12 >>> lst1.pop() #Remove the end 13 'd'14 >>> lst115 ['z', 'a', 'b', 'c'] 16 >>> lst1.remove('z') #Delete the specified element 17 >>> lst118 ['a', 'b', 'c']19 >>> lst1 = [ 'a', 'b', 'c', 'd']20 >>> lst2 = lst1.copy() # Only shallow copy python3 has 21 >>> lst2 = lst1.copy() 22 >>> lst223 ['a', 'b', 'c', 'd']24 >>> lst2.clear() #Clear the list 25 >>> lst226 [] 27 >>> del lst2 #Delete list 28 >>> lst129 ['d', 'c', 'b', 'a']30 >>> lst1.sort() # Sort 31 >>> lst132 ['a', 'b', 'c', 'd']33 >>> lst1.append('a')34 >>> lst1. count('a') #Count 35 236 >>> lst137 ['a', 'b', 'c', 'd', 'a']38 >>> len(lst1) # Length 39 540 >>> lst1.index('a') #Index 41 042 >>> lst1.index('a',1) #Index 43 4
View Code
Dictionary
1 >>> dic1 = {'key1' : 'a','key2' : 'b'} 2 >>> dic1.get('key1') #Get the dictionary value, not found Returns None by default, you can also specify 3 'a' 4 >>> dic1.get('key3') 5 >>> dic1.items() 6 dict_items([('key2', 'b' ), ('key1', 'a')]) #Return tuple list 7 >>> list(dic1.items()) 8 [('key2', 'b'), ('key1', 'a')] 9 >>> dic1.keys() #Return keys list 10 dict_keys(['key2', 'key1'])11 >>> dic1.values() #Return value list 12 dict_values(['b', 'a'])13 >>> dic2 = dic1.copy() #Shallow copy 14 >>> dic215 {'key2': 'b', 'key1' : 'a'}16 >>> dic1['key3'] = 'c' #Assignment (modification)17 >>> dic118 {'key2': 'b', 'key1': 'a ', 'key3': 'c'}19 >>> dic1.pop('key1') #Delete the specified key20 'a'21 >>> dic122 {'key2': 'b', 'key3': 'c'}23 >>> dic1.get('key1','a') #Value, no 'a'24 'a'25 >>> dic126 {' key2': 'b', 'key3': 'c'}27 >>> dic1.setdefault('key1','a') #Set the default (seems useless) 28 'a'29 >> ;> dic130 {'key2': 'b', 'key1': 'a', 'key3': 'c'}31 >>> dic3 = {'name':'update'}32 > >> dic1.update(dic3) #Update 33 >>> dic1 34 {'key2': 'b', 'name': 'update', 'key1': 'a', 'key3': 'c'}35 >>> del dic3 #Delete 36 >>> dic137 {'key2': 'b', 'name': 'update', 'key1': 'a', 'key3 ': 'c'}38 >>> len(dic1) #Length 39 4
View Code
The above is the content of python basic one. For more related articles, please pay attention to the PHP Chinese website (www.php. cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Fastapi ...
