Python from beginner to proficient (Day 1)

Source: Internet
Author: User
1. Key points

(1) There is no string in the C language, only characters,

In Python, the string hello, in C is a character array in memory storage [' H ', ' e ', ' l ', ' l ', ' o '], if the string is modified, then a new space is opened in memory for storage.

String attribute: Once modified, it needs to be recreated.

Example: "Hello" + "ni" + "Hao" in Memory: [' h ', ' e ', ' l ', ' l ', ' o '] + [' n ', ' I '] + [' h ', ' A ', ' O ']

The evil "+", "+" number more, in memory repeatedly created, wasted space.

The C language requires manual recycling, while high-level languages such as python,c# have virtual opportunities for GC garbage collection with no called Memory access space.

(2) The format of the Python string (placeholder) can save memory space, there are two ways, such as:

Note: The second format method will be better, the performance is better, in fact, the value of variable A does not change, in the format of the assignment will be in the memory of new space storage. Same test results in python2.7 and python3.4

>>> a = ' I am%s,age is%d ' >>> a% (' Wangkai ', ") ' I am Wangkai,age is" >>> print (a) I am%s,ag E is%d>>> a = ' I am {0},age are {1} ' >>> A.format (' Wangkai ', ') ' I am wangkai,age is ' >>> pri NT (a) I am {0},age is {1}

(3) In Python will generate a cache pool to save memory space, mainly the use of strings and numbers, so within a certain range of variables assigned the same value, their ID value is the same, when outside the pool, the ID value will be different

Tested in python2.7 and python3.4 versions, with the following test results: (tested in python2.7 and python3.4)

For strings, unlimited

>>> a = ' asdfsafsafasfsafasdfasfasfasf ' >>> b = ' asdfsafsafasfsafasdfasfasfasf ' >>> ID (a), ID (b) (140704388394128, 140704388394128) >>> a = ' ni ' >>> b = ' ni ' >>> ID (a), id (b) (140704388417416, 140704388417416)

For numbers, range: less than-5, greater than 256

>>> a = -5>>> B = -5>>> ID (a), id (b) (8745920, 8745920) >>> a = -6>>> B = -6> >> ID (a), id (b) (140718131946128, 140718131946320) >>> aa=256>>> bb=256>>> ID (AA), ID ( BB) (8754272, 8754272) >>> AA = 257   >>> bb = 257    >>> ID (AA), ID (BB) (19083048, 18637656)

The specific Python source code defines the numbers as follows:

(4) Python internal execution process:

(5) Print Description:

The print statement in Python 2 is replaced by the print () function in Python 3, which means that in Python 3 you must enclose the object that you want to output in parentheses.

Special note: Tested in python2.6, python2.7,print as a statement, but supported by brackets, example: A = 1 print a print (a) can be;

In the python3.4 version, print acts as a function and supports only parentheses.

Recommendation: For code compatibility on Python2 and 3, use the PRINT function bracket directly.

2. Code Conversion

General hard disk storage is utf-8, read into in-memory Unicode, and how they are converted

A = ' Hello ' \xe4\xbd\xa0\xe5\xa5\xbd '

b = u ' Hello ' u ' \u4f60\u597d '

A.decode (' utf-8 ') u ' \u4f60\u597d ' (utf-8 format decoded to Unicode)

B.encode (' utf-8 ') ' \XE4\XBD\XA0\XE5\XA5\XBD ' (Unicode format encrypted to Utf-8)

Note: In the python2.7 version you need to convert as above, in the script to display Chinese,

Just add # _*_ coding:utf-8 _*_ or #coding =utf-8 at the beginning of the file.

After the python3.4 version, no conversion is required

3. Call the system command and deposit the variable:

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.ARGV

Sys.path

5. Import Template Method:

1.import sys [as newname]

When the import statement is reused multiple times, 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 ()

The reload will reload the loaded module, but the original instance will still use the old module, and the newly produced instance uses the new module, or the original memory address after reload; Import: The module in the format is reloaded.

It is recommended that the first, the second imported object or variable will conflict with the current variable.

6. User interaction:

In the python2.7 version

Raw_input: The interactive input content is converted into a string;

Input: The interactive input content does not convert;

In the python3.4 version only input, want to get the number, need to make an int transformation.

Example:

#_ *_ Coding:utf-8 _*_info = ' This var would be a printed out ... ' name = raw_input (' Please input your name: ') age = Int (raw_inp UT (' Age: '))  #age = input (' Age: ') job = raw_input (' job: ') salary = input (' Salary: ') print type ' print ' ' Personal Information of%s:     Name:%s Age      :%d     Job:%s    Salary:%d--------------------------"% (Name,name, age,j Ob,salary)

7, user input content hiding:

When entering a password, if you want to be invisible, you need to take advantage of the Getpass method in the Getpass module, namely:

>>> import getpass>>> pwd = getpass.getpass ("Please input the passwd:") please input the passwd:>> > Print (PWD) ASDFASDFA

8. File Operation:

File and open files can be opened in version python2.7, only open in python3.4 version

f = open (' file_name ', ' R ')

g = File (' file_name ', ' R ')

Where open mode has ' R ', ' W, ', ' A ', ' B ', ' + '

W: Replace rewrite a: append

B: Binary file, mainly used for cross-platform, to solve window and Linux carriage return line difference

+: For simultaneous reading and writing

* The end of the newline character f.readline () is generally removed from the first line read by the file. Strip (' \ n ')

* Xreadlines: For large files, one line reads, the default is to read the full file into memory.

* r+: Read-write, by default written from the end of the file, you can jump to the specified location by seek, and then replace the file contents.

Initial file Aa.txt

Kevin:123:1
Wang:22:2
Kai:311:3

The python2.7 and python3.4 test results are the same.

# _*_ coding:utf-8 _*_import sys,osfile = sys.argv[1]f = open (file, ' r+ ') line_list = F.readlines () new_list = []for line in Line_list:  #去掉行尾的换行符 Line  = Line.strip (' \ n ')  #对行信息按分隔符进行分列  value_list = Line.split (': ')  # Get the last field and digitize  last_value = Int (value_list[-1])  #对最后一字段进行数字计算  last_value *=  value_list[-1] = str ( Last_value)  #将列表转变为字符串  new_str = ': '. Join (value_list)  #将循环的改变后的行追加到新的列表  new_list.append (new_ STR) '  ##### #第一种方法按行追加到文件 #####  #按修改后的行追加到文件中  #f. Writelines (new_str + ' \ n ') "##### The second method appends all rows uniformly to the file ##### #将所有修改后的新列表转化为字符串my_str = ' \ n '. Join (New_list) #将指标移到行首f. Seek (0) #将写回到文件f. Write (my_str + ' \ n ') ' ' F.close ()

9. Type change:

Python has a way to convert any value into a string: pass it to the REPR () or str () function.

The function str () is used to convert a value into a form suitable for human reading, while REPR () translates into a form for the interpreter to read (if there is no equivalent
Syntax, syntaxerror exception occurs) if an object does not have an explanatory form suitable for human reading, STR () returns a value equal to repr (). Many types, such as numerical or linked lists, dictionaries, have a uniform interpretation of each function. Strings and floating-point numbers have a unique way of interpreting them.
Some Examples:

Here are some examples

>>> s = ' Hello, world ' >>> Str (s) ' Hello, World ' >>> repr (s) "' Hello, world. '" >>> str (1.0/7.0) ' 0.142857142857 ' >>> repr (1.0/7.0) ' 0.14285714285714285 '
  • 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.