Python self-taught day-2

Source: Internet
Author: User
Tags id3 shallow copy

First, the module The modules are divided into two types:Standard libraries and third-party libraries, which are libraries that you do not need to install. import [module name]:Importing a library takes precedence over the project path. The custom module name should not be the same as the standard library module name. SYS module:
Import Sys
Print (Sys.path)
The Sys.path holds the Python internal call or the lookup path of the module. The results are as follows:

[' D:\\pycharm_workspace\\firstproject\\day2 ',

' D:\\pycharm_workspace\\firstproject ',' D:\\python36\\python36.zip ',' D:\\python36\\dlls ',' D:\\python36\\lib ',' d:\\python36 ',' d:\\python36\\lib\\site-packages '] The third-party libraries installed in ' d:\\python36\\lib\\site-packages ' are primarily stored. ' D:\\python36\\lib ' mainly put the standard library.
Import Sys
Print (SYS.ARGV)
SYS.ARGV Save the parameter, the first parameter is the relative path of the module file, and the following parameters are added together to form a list. OS module:
Import OS
Os.system ("dir") #只执行命令, do not save results
Os.system () executes a system command. Direct output to the screen, can not be stored in the variable, the method returns the status code (0 is successful).
Import OS
Cmd_res = Os.popen ("dir"). Read ()
Print (Cmd_res)
Os.popen ("dir") executes the dir command and stores the result in an area of memory, which requires read () reading results.
Import OS
Os.mkdir ("New_dir")
Os.mkdir ("New_dir") to create a new directory in the current path. An exception is thrown when the directory already exists. third-party modules:That is, the custom py file (test.py). Import the module in a different py file. Use import test. If the IDE prompts the module, no modules named Test. Right-click on the project directory or the directory containing the file and select Mark Directory As->source Root. Second, PYc     After executing a module, a __pycache__ folder appears in the code files directory that has a PYC file corresponding to the module name.    such as MODULE1.CPYTHON-36.PYC.    With the rise of virtual machine-based languages such as Java, it is not possible to divide the language purely into explanatory and compiled types. Java is first compiled into a bytecode file by a compiler and then interpreted as a machine code by the interpreter at run time. So we say that Java is a language that is compiled and interpreted first. What is python exactly:Pyhton, like Java/c#, is also a virtual machine-based language. It is also a language that is first compiled and interpreted. third, python execution process Pycodeobject:Is the result compiled by the Pyhton compiler. When the Python program runs, the compilation results are saved in an in-memory Pycodeobject, and are written back to the PYc file after the run is finished. When the program executes for the second time, it will first look for the PYc file on the hard disk, find it and load it directly, or repeat the compilation process. If the PYC update time is older than the source code time, it needs to be recompiled. Iv. Initial knowledge of data types int:In the C language, 32-bit machines can only be stored in -2**31~2**31-1, or -2147483648~2147483647. 64-bit machine memory -2**63~2**63-1. There is no limit to the size of integer values in Python, in fact machine memory is limited and integer values are not infinite. For example, print (type 2**100), the output is int. float:Decimals, for example 3.23. Science counts, 5.2E-4, equivalent to 5.2*10**-4. Boolean value:True or False (Ture/false), 1 or 0 (only 1 and 0 represent true and false). five or three-dollar operationresult = value 1 if condition else value 2. That is, when the IF condition is true, result is a value of 1, otherwise the value is 2.eg.
A,b,c = 1,3,5
result = A If a>b else C
Print (Result)
vi. bytes and strIn Python3, a clearer distinction is made between text and binary data.    Text is always Unicode, and STR indicates that binary data has a bytes type representation. Str and bytes can be converted between each other. As shown: eg.
msg = "I love Beijing Tian An men". Encode ("Utf-8")
Print (msg)
msg = Msg.decode ("Utf-8")
Print (msg)
Will "I love Beijing tian an door" using encode () encoded into binary, parameters specify the text to be converted to Utf-8, the default is Utf-8. Then decode () is decoded into text. Vii. List define a list:names = [],names = ["Leo", "Alex", "Jack", "Leno"] take a value:Names[index], such as names[1], take out Alex. slices: take a range of values:Names[1:3], take out ["Alex", "Jack"], the left 1 contains, the right 3 is not included. Names[0:3] and Names[:3] are the same. take the last value:NAMES[-1], remove the Leno. take the value of the last paragraph:Names[-2:], remove ["Jack", "Leno"]. Skipping slices:Names[0:-1:2], from the first one to the penultimate one, not one to skip one. Append (append):Names.append ("Cheng Long"). inserting (insert):Names.insert (1, "Cheng Long"), put Jackie to the position of index 1, followed by the name of the next move. Replacement:Names[1] = "Yang Mi", write directly to a location and replace Jackie Chan with Yang Mi. Delete (remove):Three methods: Names.remove ("Yang Mi"). Del Names[1]. Names.pop (1). Pop () If the subscript is not filled in, the last one is deleted by default. find Subscript (index):Names.index ("Yang Mi"), returns the subscript of the first Yang Mi. Purge (Clear):Names.clear () Flip (reverse):Names.reverse () Sorting (sort):Names.sort (). The default is special characters > numbers > Uppercase > Lowercase, sorted by ASCII code. merge (Extend):Names.extend (Names2). Add the Names2 list to the names behind. Name2 still exists after merging. Copy:Names2 = Names.copy (). Copy only the first layer of data, as a shallow copy.The second layer is a stored reference, so the copy is a pointer. Pay attention!!! eg.
names = [1,2,3,[' A ', ' B '],4,5]
Names2 = Names.copy ()
NAMES2[2] = 10
Names2[3][1] = ' C '
Print (names)
Print (Names2)
the first layer of data is completely copy. The second layer of data is not copy,copy the memory address. Together point to the same piece of memory area.         To use a real copy, you need to import the copy module:
Import Copy
names = [1,2,3,[' A ', ' B '],4,5]
Names2 = copy.copy (names) #和list中的copy是一摸一样的
Names3 = copy.deepcopy (names) #深度copy, copy in the true sense. But use less, accounting for two full memory space.
List loop:
num = [0,1,2,3,4,5,6,7,8,9,10]
For I in Num[0:-1:2]:
Print (i)
Eight, the tupleThat is, immutable lists, which can be called read-only lists.    Use () to indicate. Names = ("192.168.1.100", "admin", "passwd") for example, use tuples to save immutable data, such as database connection information. Nine, whether the value of the judgment is numeric
num = input ("Please input a num")
If Num.isdigit ():
num = int (num)
10. String Manipulation   The value of a string cannot be changed, and all changes made on the string are internally recreated with a string to overwrite the original string. name = "Leo Zheng Leokale" initial Capitalization (capitalize):Name.capitalize (), output "Leo Zheng Leokale" Count the number of letters or occurrences of a string (counted):Name.count (' e '), Output 2. Name.count (' Leo '), Output 2. Fill and Center (center):Name.center (50, "*"), if the string in name is not 50 characters long enough, fill 50 with ' * '.        and centers the string of name. Leo Zheng leokale***************** determines whether a character end is specified (EndsWith):Name.endswith (' Le '), output true. convert tab to a specified number of spaces (Expandtabs):Name = "Leo \tzheng" name.expandtabs (tabsize = 30), convert \ t to 30 spaces. finds the index of the specified character or string (find):Name.find (' o '), Output 2. The default is to find only the first one. or Name.find (' ka '), return 13. Formatting (format) (common):name = "My name is {myname}" print (Name.format (myname = "Leokale"), output "My name is Leokale".
name = "My name is {name},i am {year} years old."
Print (Name.format (name = "Leokale", year = 32))
format (format_map):
name = "My name is {name},i am {year} years old."
Print (Name.format_map ({"Name": "Leokale", "Year": 32}))
determine if it is Arabic numerals and characters (isalnum):
Print ("123". Isalnum ())   #输出True
Print ("123abc". Isalnum ())    #输出True
Print ("123abc*". Isalnum ())    #输出False
determine if it is a plain English character (isalpha):Contains case
Print ("Abcabc". Isalpha ())   #返回True
Print ("abcABC123". Isalpha ())   #返回False
determine if it is a decimal (isdecimal) determines whether an integer (isdigit) determine if it is a valid identifier (Isidentifier):That is, whether it is a valid variable name.
Print ("My_name". Isidentifier ())   #输出True
Print ("--my_name". Isidentifier ())   #输出false
Determine if all lowercase (islower) Determine if authoritative capitalization (isupper) determine if it is a pure number (IsNumeric):Almost the same as isdigit. That is, the integer is determined. to determine if it is title (istitle):That is, the first letter of each word is capitalized, the other lowercase. to determine if it is printable (isprintable):TTY file,drive file cannot be printed. to turn a queue into a string (join):
Print ("+". Join (["My", "name", ' is ', ' Leokale ')])   #输出my +name+is+leokale
Use the character padding (ljust) later:
Print ("name". Ljust (' * '))  #输出name ****************
use character padding (rjust) in front:
Print ("name". Rjust (20, ' * '))
convert all to lowercase (lower) convert all to uppercase (upper) remove the front and back spaces and newline characters (strip):
name = "  name  \ n"
Print (Name.strip ())
Remove the left space and line breaks (Lstrip) Remove the right space and line break (Rstrip)      Password Translation (Maketrans):
Name = "Leokale Good day is today"
PPP = Str.maketrans ("Leokalgdys", "123456789*") #数量要对应
Print (Name.translate (PPP))
replacement (replace):
Print ("Namea". Replace ("a", "*", 2))   #输出 n*me*
Find the return index (RFind) starting from the right:
Print ("Leokale". RFind (' l '))  #输出5
Split by a character (split):
Print ("My name is Leo". Split ())   #输出 [' My ', ' name ', ' is ', ' Leo ']
Print ("My+name+is+leo". Split (' + '))
Split by line break (Splitlines):Split by line break in different systems (different Windows and Linux). swap Case (swapcase):
Print ("name". Swapcase ())   #输出 Name
Convert to Title:
Print ("Good Thing". Title ())   #输出 Good Thing
with 0 in front complement (Zfill):Used primarily for 16-binary front with 0-bit complement. 11. DictionariesA dictionary is a key-value data type. Grammar:
info = {
' Id1 ': ' Leo ',
' Id2 ': ' Jack ',
' ID3 ': ' Alex ',
' Id4 ': ' Song '
}
    • The dict is unordered and has no subscript index. Print out, the order is chaotic.
    • Key must be unique and inherently heavy.
     Printing results:Print (info) {' id1 ': ' Leo ', ' id2 ': ' Jack ', ' id3 ': ' Alex ', ' id4 ': ' Song '} Value:
Print (info[' id1 ')   #输出 Leo
Modify:
info[' id1 '] = ' Kale '
Print (info[' id1 ') #输出 Kale
Add an article:ID5 is not present, it is added.
info[' id5 'Lily'
Delete:
Del info[' Id2 ']
Print (info)
Info.pop (' Id2 ')
Print (info)
Info.popitem ()   #随机删除一个
Print (info)
Find:
If ' id1 ' in info:   # ' id1 ' in info, if there is a return of true, there is no return false. Lists and tuples can also be judged this way.
Print ("ID1 exists")
Dictionary nesting:
info = {
' Id1 ': {
' Name ': ' Leo ',
' Age ': 32
},
' Id2 ': {
' Name ': ' Boob ',
' Age ': 12
},
' ID3 ': {
' Name ': ' Alex ',
' Age ': 22
},
' Id4 ': {
' Name ': ' Jack ',
' Age ': 56
}
}
to modify the age in Id2:
info[' Id2 ' [' age '] = 44
Print (info)
Value is created if it does not exist, and the value is removed if it exists (SetDefault):
Info.setdefault (' Id5 ', {' name ': ' Enrique '})
Print (info) #添加了id5, name Enrique
Info.setdefault (' Id5 ', {' name ': "Fujiwara Love"})
Print (info) #已经存在id5, return {' name ': ' Enrique '}
Updated (update):If the key between info and Info2 is crossed, use the content in Info2 instead. The part that doesn't intersect is created in info.
Info2 = {
' Id1 ': {
1:2,
2:3
}
}
Info.update (Info2)
convert the dictionary to a list, with each key-value converted to a tuple:
Print (Info.items ())  #输出dict_items ([' Id1 ', {1:2, 2:3}), (' Id2 ', {' name ': ' Boob ', ' age ': ') ', (' id3 ', {' name ': ' Alex ' Age ': '), (' Id4 ', {' name ': ' Jack ', ' Age ': 56})])
Info_list = List (Info.items ())
Initialize a dictionary (fromkeys):
Dict1 = Dict.fromkeys ([1,2,3,4], "test")
Print (DICT1)
Here, if the second parameter of Fromkeys is two-storey structure. The value corresponding to each key is dict1 a reference. Modify one of them and all will change.
Dict1 = Dict.fromkeys ([1,2,3,4],{' name ': ' Leo '})
dict1[1][' name '] = "Jack"
Print (Dict1) #输出 {1: {' name ': ' Jack '}, 2: {' name ': ' Jack '}, 3: {' name ': ' Jack '}, 4: {' name ': ' Jack '}}
Loop read:
For key in info:   #建议使用这种, efficient.
Print (Key,info[key])
For k,v in Info.items ():   #有一个把字典转换为列表的过程, the efficiency is low, the data is large when the time to manifest.
Print (K,V)

Python self-taught day-2

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.