---restore content starts---
Python file
File at the beginning of the #!/usr/bin/python--in Linux is to tell the system Phthon path is in the/usr/bin/python directory, in the execution of Python files can be used./file name, such as:./h.py can be executed
So the python2.7 file needs to have a #-*-coding:utf-8-*-This sentence to set the encoding format
When there is Chinese output, often output is garbled, this is because the code is UTF-8 format, but the display terminal encoding format is GBK format. If the format of the display terminal is Utf-8, it will display normally, but if it is in GBK format, it is garbled. The UTF-8 encoding and GBK encoding are Unicode (universal code) simplification and optimization, but the encoding method is not the same. To solve the problem of Chinese output display garbled, you need to decode the utf-8 format into Unicode, and then the GBK encoding, and then output, you can display Chinese normally, as follows:
-
1 #-*-coding:utf-8-*-2 3temp ="Hello"4 5 #first decode the utf-8 to Unicode6 7Temp_unicode = Tem.decode (' Utf-8 ')#the utf-8 here is to specify that the original encoding is UTF-8 encoded8 9TEMP_GBK = Temp_unicode.encode ("GBK")#the GBK here is to specify the encoding in GBK formatTen One Print(TEMP_GBK) A - #to the PY3, the auto-convert utf-8 Unicode gbk,utf-8 can be encoded directly into the GBK - the #The Unicode type of Python was removed from Py3
Enter python in the cmd command window to enter the Pythod environment, enter exit () to exit the editing environment
Comments
Single-line comment, using #
Multi-line comment, using "" "" "" "" "" ""
Import file
. py files that Python provides to users
Import file name (without. py) after importing with import
A. PYc bytecode file with the same name is automatically generated after executing the program, which is equivalent to caching the file
Execution takes precedence of the. pyc file and executes if the. pyc file is not found, then you'll find the. py file and Execute
Get input text
I1 = Raw_input ("Username:") for text entry in plaintext
I2 = Getpass.getpass ("Password:") (Import a file before using this sentence imports Getpass)
Create a xxx.py file
Suggested file name, storage path do not have Chinese
Two lines of the head of the code is more special, must have
Basic data types
Number: A1 = 123
String: S1 = "abc" or s2 = ' abc ' or s3= "" "CDE" "(content in three quotation marks is a multiline text string)
Boolean value: Isable = True
Process Control
If
If condition: Content One Content II Elif Conditions: Content Five Content Six else: Content Three Content Four |
Python is executed strictly by indentation.
An equal sign is an assignment, two equals is a comparison,! = is not equal to
While
While condition: Content One |
Time.sleep (1) Pause for 1 seconds
Break, you can jump out of the loop
Continue, jump out of this cycle and continue the next cycle.
Pass, do not do anything, can not be empty, write a pass can
For loop
S7 = "Return a copy of the string" for item in S7: Print Item |
Enumerate ()
The Accept parameter can be a list
Automatically generates a column for the list item when used in for loop, default starting from 0, increment 1
Li = ["Computer", "iphone", "Watch", "Car"]for Key,item in Enumerate (LI): print (key,item) INP = input ("Please enter Product:") inp_ num = Int (INP) print (Li[inp_num]) ------------------------Output------------------------- (0, ' computer ') (1, ' iphone ') (2, ' Watch ') (3, ' Car ') Please enter product: 0 Computer |
Operator
Arithmetic operations
+-*/% (take balance) * * (power, returns the y power of X)//(Take an integer, return the integer part of the quotient)
PY2:9/2 = 4 9/2=4.5 (need to import modules, such as: from __future__ Import Division) PY3:9/2 = 4.5 |
-
-
pycharm Set the template for the Py file, adding a fixed two lines to the header: Fileàsettingàedit Oràfile and Code Templateàpython script, enter a fixed two lines Àok
-
pycharm Switch the py version, FILEÀSETTINGSÀPROJEC T Interpreterà Select version
-
comparison operator: == != <> > < >= < =
-
assignment operator: = += -= *= /= %= **=
-
&nb Sp;ctrl +/ Comment shortcut
-
logical operator:and or not
-
Member operator: in Not in
-
base data type
-
Numbers int
-
The method of __ in the Int class is a method with special functions
N1 = 123 N2 = 456 Print (n1 + N2) is equivalent to print (n1.__add__ (n2)) |
Bit_length (), gets the number of binary shortest digits that can be represented
N1 = 4 #00000100 ret = N1.bet_length () Print (ret) |
String str
Capitalize () method, capitalize first letter
Center (length, blank padding character) method to display the current string in the middle, with the blank part replaced with the specified character
Count () method, number of sub-sequences, number of occurrences of the current string in the specified string
Decode () method, decoding
Encode () method, encoding
EndsWith () method, [Gets the position of the string greater than or equal to 0, the position less than 2], whether to end with XXX
Expandtabs () method to convert the tab (\ T) to a space (default 8 spaces)
The Find () method, which finds the first occurrence of a subsequence, returns 1 if not found
Format () method, string serialization
s = "Hello {0}, age {1}" print (s) s2 = S.format ("Alex") print (s2) ------------------------Output------------------------- Hello {0}, age {1} Hello Alex, age 20 |
Index () method, find the position of the sub-sequence, if not found, error
int (string) to convert the specified string to a number and return
Isalnum () method to determine if there are both letters and numbers
Isalpha () method to determine if all letters are
IsDigit () method to determine whether a number
Islower () method to determine if lowercase
Isspace () method to determine whether it is a space
Istitle () method to determine if the title (the first letter of each word is capitalized)
Join () method, connecting
Li = ["Alex", "eric"]s3 = "_". Join (LI) print (S3) ------------------------Output------------------------- Alex_eric |
-
Ljust () method, content alignment, right padding, similar to center ()
-
Lower () method, lowercase
-
Len () method, return Back to string length
-
Lstrip () method, remove left blank
-
Partition () method, split string into left-right three-part
-
Split () method, split word String
-
Replace () method, replace strings
-
RFind () method, looking right-to-left
-
Rindex () method, similar to Lindex (), Just here is to find the
-
Rjust () method from right to left, similar to Ljust (), in the opposite direction to Ljust () the
-
Rpartition () method, similar to partition (), The direction is opposite to partition () the
-
Rsplit () method, similar to the split () method, in the opposite direction of Split ()
-
Rstrip () method, similar to the Lstrip () method , the direction is opposite to the Lstrip ()
-
Strip () method, removing the left and right spaces
-
StartsWith () method to determine whether a string starts with the specified string
-
Swapcase () method, lowercase to uppercase, uppercase to lowercase
-
Title () method to turn text into a caption
-
Upper () method to convert text to uppercase
-
Slice
S6 = "Alex" Print (S6[0:2]) #大于等于左边, less than the right ------------------------output------------------------- Al |
-
-
Boolean bool
- p> lists list
-
Append () method, append element
li> the
-
Count () method to count the number of
-
Extend () methods for an element to append data to the list
-
Index () method to get the index of an element
li> the
-
Insert () method, inserts an element at an index
-
Pop () method, removes the last element, and can return the removed element
-
Remove () method to remove a element, only remove the first
-
Reverse () method found from the left, reverse the list
-
Sort () method, sort the list
-
del list [index], Delete List the elements of the specified index
-
Tuples tuples
-
Tuples are almost the same as lists, lists can be modified, tuples cannot be modified
-
Dictionary & nbsp; dict
-
Each element of the dictionary is a key-value pair, a bit similar to a simple JSON object
user_info = {"Name": "Alex", "Age": "Gender": "M"} |
-
The index of the dictionary element is the corresponding key string
-
Dictionary does not support slicing
-
Keys () method, get all keys in dictionary
-
Values () method to get all value
-
Items () Methods in the dictionary, getting all the key values in the dictionary
-
For loop
-
For Loop when dictionary, the default output key is: For k in User_info is equivalent to a for K in User_info.keys ()
-
If you want to loop out the value of the dictionary: for-V in User_info.values ()
li>
If you want to loop out the keys and values of the dictionary at the same time: for K,v in User_info.items ()
-
Clear () method, empty all elements in the dictionary
-
G The ET () method, gets the value from key, if key does not exist, you can specify an arbitrary value
-
Haskey () method, check whether the specified key in the dictionary exists, or use in instead of the
-
Pop () method, Gets and removes the
-
SetDefault () method in the dictionary, creates if the key does not exist, returns the existing value if it exists, and does not modify the
-
Update () method, UPDATE, To update an element in one dictionary to another after the
-
del dictionary [key], delete the element that specifies key for the dictionary
Range, xrange
Range, which is used in py2.7 to get a number within a specified range, such as range (0,1000000), creates a range of numbers at a stroke, and memory consumption rises rapidly
Xrange, which is used in py2.7 to get a number within a specified range, such as range (0,1000000), does not initially create a number in the range, only one element in its range is created in the For loop, and performance is greatly improved
In Py3, there is no xrange, but range, but the effect is the same as the xrange effect in py2.7
Range (0,10), get all the numbers between 0~9, take the number range is greater than or equal to the left number, less than the right number
Li = ["Computer", "iphone", "Watch", "Car"]n = Len (li) for I in Range (0,n): print (I,li[i]) ------------------------Output------------------------- (0, ' computer ') (1, ' iphone ') (2, ' Watch ') (3, ' Car ') |
View the class of an object, or the functionality that an object has
The type (variable) function can see the data type of the variable, and then, depending on Ctrl + Left, view all internal methods
DIR (variable) for a quick look at all the methods of variable types
Help (Type (variable)) to see a detailed method of variable type
Python basic syntax, basic data types, and related operations