From getting started with python (DAY 1 ),

Source: Internet
Author: User

From getting started with python (DAY 1 ),

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) formatting (placeholder) a python string can save memory space. There are two methods, for example:

Note: The second format method provides better results and better performance. In fact, the value of variable a has not changed. During formatting and assignment, it will store new spaces in the memory. The test results in python2.7 and python3.4 are the same.

 >>> a = 'i am %s,age is %d'>>> a % ('wangkai',33)'i am wangkai,age is 33'>>> print(a)i am %s,age is %d>>> a = 'i am {0},age is {1}' >>> a.format('wangkai',33) 'i am wangkai,age is 33'>>> print(a)i am {0},age is {1}

(3) In python, a cache pool is generated to save memory space. It mainly stores frequently used strings and numbers. Therefore, the variable is assigned the same value 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, 140704388394128)>>> a = 'ni'>>> b = 'ni'>>> id(a),id(b)(140704388417416, 140704388417416)

For numbers in the range of-5 and 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 python source code defines 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 the objects to be output must be enclosed in parentheses in Python 3.

Note: print is used as a statement in python2.6, python2.7, but brackets are supported, for example, a = 1 print a print (;

In python3.4, print is used as a function and only supports the brackets.

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

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 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)

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)asdfasdfa

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, which is written from the end of the file by default. You can switch from seek to the specified position and replace the file content.

Example file aa.txt

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

The test results for python2.7 and python3.4 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: # Remove the line break at the end of the line = line. strip ('\ n') # value_list = line. split (':') # obtain the last field and digitize it. last_value = int (value_list [-1]) # last_value * = 13 value_list [-1] = str (last_value) # convert the list to the string new_str = ':'. join (value_list) # append the row after changing the loop to the new list new_list.append (new_str) ''' ###### Method 1: append data to a file by row ##### append data to a file by the modified row # f. writelines (new_str + '\ n ') ''''' ##### the second method is to append all rows to a file ##### convert all the modified lists to the string my_str =' \ n '. join (new_list) # Move the indicator to the beginning of the row f. seek (0) # write back to file f. write (my_str + '\ n') ''' f. close ()

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.142857142857'>>> repr(1.0/7.0)'0.14285714285714285'

Articles you may be interested in:
  • Basic knowledge about Python
  • Python3 is simple but not bad
  • Getting started with Numpy in Python
  • Python Study Notes (1) (Basic Environment setup)
  • Functions in getting started with Python
  • Full record of crawler writing for python Crawlers
  • No basic write python crawler: Use Scrapy framework to write Crawlers

Related Article

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.