Python learning notes (Day 1) and python learning notes
1. Key Points
(1) There are no strings in C, only characters,
In python, the string hello is stored in the memory as a character array in C ['h', 'E', 'l', 'l', 'O']. if you modify the string, a new space is opened in the memory for storage.
String feature: Once modified, it needs to be re-created.
For example: "hello" + "ni" + "hao" memory: ['h', 'E', 'l', 'l ', 'o'] + ['n', 'I'] + ['h', 'A', 'O']
The more "+" and "+" are, the more times they are created in the memory, which wastes space.
C language needs to be manually recycled, while python, C # and other advanced languages have their own virtual opportunities for GC garbage collection without calling memory access space.
(2) In python, a cache pool is generated to save memory space. It mainly stores frequently used strings and numbers. Therefore, the same value is assigned to the variable within a certain range, their id values are the same. When the pool is exceeded, the id values are different.
The test results in python2.7 and python3.4 are as follows: (the test results are the same in python2.7 and python3.4)
Unlimited for strings
>>> A = 'asdfsafsafasfsafasdfasfasfasf' >>> B = 'asdfsafsafasfsafasdfasfasfasf'> id (a), id (B) (140704388394128,140 704388394128) >>>> a = 'ni' >>> B = 'ni' >>> id (a), id (B) (140704388417416,140 704388316416)Character instance
For numbers in the range of-5 and greater than 256
>>> A =-5 >>> B =-5 >>> id (a), id (B) (8745920,874 5920) >>> a =-6 >>> B =-6 >>> id (a), id (B) (140718131946128,140 718131946320) >>> aa = 256 >>>> bb = 256 >>> id (aa), id (bb) (8754272,875 4272) >>> aa = 257 >>>> bb = 257 >>> id (aa), id (bb) (19083048,186 37656)Digital instance
The python source code defines numbers as follows:
Suggestion: To ensure code compatibility on python2 and 3, use the print function brackets directly.
2. encoding conversion
Generally, the hard disk is stored in UTF-8, And the READ memory is unicode. How can they be converted?
A = ''\ xe4 \ xbd \ xa0 \ xe5 \ xa5 \ xbd' <type 'str'>
B = U' 'U' \ u4f60 \ u597d '<type 'unicode'>
A. decode ('utf-8') U' \ u4f60 \ u597d '(unicode is decoded in UTF-8 format)
B. encode ('utf-8') '\ xe4 \ xbd \ xa0 \ xe5 \ xa5 \ xbd' (unicode format is encrypted to UTF-8)
Note: The above conversion is required in python2.7. To display Chinese characters in the script,
Just add # _ * _ coding: UTF-8 _ * _ or # coding = UTF-8 at the beginning of the file.
Versions later than python3.4 do not need to be converted
3. Call system commands and store the variables:
1. import OS
A = OS. system ('df-th ')
B = OS. popen ('df-th', 'R') returns a file object.
2. import commands
C = commands. getoutput ('df-th') returns a string
4. sys call
Import sys
Sys. exit
Print sys. arg
Sys. path
5. Import template method:
1. import sys [as newname]
When the import Statement is repeatedly used, the specified module is not reloaded, but the memory address of the module is referenced to the local variable environment.
2. from sys import argv or (*)
3. reload ()
Reload will re-load the loaded modules, but the old modules will still be used for the original instances, and the new modules will be used for the new production instances; the original memory address is used after reload; from is not supported .. Import .. Format.
We recommend that you use the first method. The second method imports objects or variables that conflict with the current variables.
6. User Interaction:
In python2.7
Raw_input: the interactive input content is converted to a string;
Input: Interactive input content is not converted;
In python3.4, only raw_input is supported. int conversion is required to obtain numbers.
Example:
# _ * _ Coding: UTF-8 _ * _ info = 'this var will be printed out... 'name = raw_input ('Please input your name: ') age = int (raw_input ('Age:') # age = input ('Age :') job = raw_input ('job: ') salary = input ('salary:') print type (age) print ''' Personal information of % s: Name: % s Age: % d Job: % s Salary: % d ------------------------ ''' % (name, name, age, job, salary)User interaction instance
7. Hide user input:
When entering the password, if you want to be invisible, you need to use the getpass method in the getpass module, that is:
>>> Import getpass >>> pwd = getpass. getpass ("please input the passwd:") please input the passwd :>>> print (pwd) asdfasdfaHide input characters
8. File Operations:
In python2.7, you can use file and open to open files. In python3.4, only open
F = open ('file _ name', 'R ')
G = file ('file _ name', 'R ')
The open modes include 'R', 'w, ', 'A',' B ',' +'
W: replace override a: append
B: binary files are mainly used across platforms to solve the differences between window and linux carriage return.
+: Used for simultaneous read/write
*Generally, the line break f. readline (). strip ('\ n') at the end is removed from the first line read by the file ')
*Xreadlines: for large files, one row is read. By default, the entire file is read into the memory.
*R +: read/write. By default, data is written from the end of the file. You can switch from seek to the specified position and replace the file content.
Example: f = open ('file _ name', 'r + ')
F. seek (50)
A = range (10)
A = [str (I) + '\ n' for I in a]
F. writelines ()
9. Type Change:
Python can convert any value into a string: Pass it into the repr () or str () function.
The str () function is used to convert a value into a form suitable for human reading, while repr () is converted into a form for the interpreter to read (if there is no equivalent
SyntaxError occurs. If an object does not have an interpreted form suitable for reading, str () returns the value equivalent to repr. Many types, such as numeric values, linked lists, and dictionaries, have a unified interpretation method for each function. String and floating point number, with a unique interpretation method.
Some examples:
Some examples below
>>> S = 'hello, world .'
>>> Str (s)
'Hello, world .'
>>> Repr (s)
"'Hello, world .'"
>>> Str (1.0/7.0)
'0. 100'
>>> Repr (1.0/7.0)
'0. 100'
10. dictionary replication:
Dict = {'name': 'wang', 'sex': 'M', 'age': 34, 'job': 'it '}
Info = dict # Alias (the two dictionaries point to the same address space in the memory)
Info1 = dict. copy () # shadow copy (the first layer of the nested dictionary is independent and associated below the second layer)
Import copy
Copy. copy () # shadow copy
Copy. deepcopy () # deep copy (completely independent)
Note: The associations in the light replication mode are only for the nested objects contained in the dictionary's initial state. Newly Added objects will not
Example:
>>> Dict
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'sex': 'M', 'age ': 40, 'name': 'wang '}
>>> Dict_alias = dict
>>> Dict_copy = copy. copy (dict)
>>> Dict_deep = copy. deepcopy (dict)
# Adding, changing, and deleting the first-level object key values are not affected in light replication and deep Replication
>>> Dict ['age'] = 32
>>> Del dict ['sex']
>>> Dict
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'age': 32, 'name ': 'wang '}
>>> Dict_alias
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'age': 32, 'name ': 'wang '}
>>> Dict_copy
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'age': 40, 'name ': 'wang ', 'sex': 'M '}
>>> Dict_deep
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'age': 40, 'name ': 'wang ', 'sex': 'M '}
# Change or delete the original second-level object key value. The shortest copy is affected, but the deep copy is not affected.
> Dict ['info'] [2] = 100
>>> Dict
{'Info': ['A', 'B', 100, 2], 'job': 'it', 'age': 32, 'name ': 'wang '}
>>> Dict_alias
{'Info': ['A', 'B', 100, 2], 'job': 'it', 'age': 32, 'name ': 'wang '}
>>> Dict_copy
{'Info': ['A', 'B', 100, 2], 'job': 'it', 'age': 40, 'name ': 'wang ', 'sex': 'M '}
>>> Dict_deep
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'age': 40, 'name ': 'wang ', 'sex': 'M '}
# Adding second-level objects will not be affected in light replication and deep Replication
>>> Dict ['new'] = {'A': 1, 'B': 2, 'C': 5}
>>> Dict
{'Info': ['A', 'B', 100, 2], 'name': 'wang', 'age': 32, 'job ': 'it', 'new': {'A': 1, 'C': 5, 'B': 2 }}
>>> Dict_alias
{'Info': ['A', 'B', 100, 2], 'name': 'wang', 'age': 32, 'job ': 'it', 'new': {'A': 1, 'C': 5, 'B': 2 }}
>>> Dict_copy
{'Info': ['A', 'B', 100, 2], 'job': 'it', 'age': 40, 'name ': 'wang ', 'sex': 'M '}
>>> Dict_deep
{'Info': ['A', 'B', 1, 2], 'job': 'it', 'age': 40, 'name ': 'wang ', 'sex': 'M '}
11. built-in function description:
_ Name __: the main file is returned; otherwise, the file name is returned, which can be used to determine whether the main file or the import module is used;
_ File __: absolute file path;
_ Doc __: description of the beginning of the file
Example:
'''
Created by 2015-12-18
@ Author: kevin
'''
If _ name _ = '_ main __':
Print ('this is main file ')
Print (_ file __)
Print (_ doc __)