Python (iii)

Source: Internet
Author: User

Data types and Files 1.1 python dictionary

Dictionary writing Format:

    1. #!/usr/bin/env python
    2. #key-value
    3. info = {
    4. ' Stu1101 ': "zhangsan",
    5. ' Stu1102 ': "lizi",
    6. ' Stu1103 ': "wangwu",
    7. }
    • Inquire
    1. Print (info)
    2. Print ("select-->", Info["stu1101"])
    3. #names = info["stu1101"]
    4. #print (names)
    5. Print ("get-->", info.get ("stu1102")) #get方法
    6. Execution Result:
    7. {' stu1103 ': ' Wangwu ', ' stu1101 ': ' Zhangsan ', ' stu1102 ': ' Lizi '}
    8. Select--> Zhangsan
    9. Get--> Lizi
    • Increase
    1. info["stu1101"] = "add 1101"
    2. Print (info)
    3. info["stu1104"] = "xiaosan" #不存在则增加
    4. Print (info)
    5. Execution Result:
    6. {' stu1103 ': ' Wangwu ', ' stu1101 ': ' Add 1101 ', ' stu1102 ': ' Lizi '}
    7. {' stu1103 ': ' Wangwu ', ' stu1104 ': ' Xiaosan ', ' stu1101 ': ' Add 1101 ', ' stu1102 ': ' Lizi '}
    • Delete
    1. Del info["stu1103"]
    2. Print (info)
    3. Execution Result:
    4. {' stu1102 ': ' Lizi ', ' stu1101 ': ' Zhangsan '}
    • Multilevel Dictionary Nesting
    1. #!/usr/bin/env python
    2. www = {
    3. "personal Blog": {
    4. ' Name ': ["lizhong"],
    5. ' Address ': ["cloudstack.com"],
    6. },
    7. "ops Community": {
    8. ' Name ': ["bjstack"],
    9. ' Address ': ["bjstack.com"],
    10. },
    11. }
    12. Www["personal blog" ["address"][0] + = ", very good personal blog, a lot of attention!"
    13. Www["operation and Maintenance community" ["address"][0] + = ", Community activity is very high, look forward to your joining!"
    14. Print ("bash surprise--", www["personal blog" ["address"])
    15. Print ("bash surprise--", www["ops community"] [address])
    16. Execution Result:
    17. Bash has surprise--[' cloudstack.com, very good personal blog, lots of attention! ']
    18. Hit with surprise--[' bjstack.com, community activity is very high, look forward to your joining! ']
1.2 Set Set

1. Go to the weight, turn a list into a set, and then automatically go heavy.
2. Relationship test, test the intersection of two sets of data, difference set, and set the Relationship.

Create a collection of values

    1. List_1 = set{1,4,5,7,3,6,7,9}
    2. List_2 = set{2,6,0,66,22,8,4}
    • Intersection (list_1 & List_2)
    1. Print (list_1.intersection (list_2))
    • and set
    1. Print (list_1.union (list_2))
    • Subtraction
    1. Print (list_1.difference (list_2))
    2. Print (list_2.difference (list_1))
    • Subset
    1. Print (list_1.issubset (list_2))
    • Parent Set
    1. List_3 = Set ([1,3,7])
    2. Print (list_3.issubset (list_1)) #list_3是list_1的子集
    3. Print (list_1.issuperset (list_3))
    • Symmetric difference set (list_1 ^ list_2)
    1. Print (list_1.symmetric_difference (list_2)) #对称差集, removed from each other, removed two two sets of duplicate
    • Inverse difference Set

    • Add to

    1. List_1.add (999) #添加一项
    2. List_1.update ([888,777,555]) #添加多项
    3. Print (list_1)
    • Delete
    1. Print (list_1.discard (555)) #discard不存在不会报错
    2. Print (list_1.remove (888)) #remove不存在, will be error, deleted and will not return data
    3. Print (list_1)
1.3 File operations
    1. File handle = filename (' file path ', ' mode ')
    2. Note: open files in Python in two ways, open (...) and file (...) in essence, the former will call the latter for the operation of files, it is recommended to use Open.
    3. File mode has been canceled in Python3
    • 1. Open File
  1. Open File Modes are:
  2. f = Open (' db ', ' r ') # read-only mode, {default}
  3. f = Open (' db ', ' W ') # write-only mode, {unreadable; not exist then create; delete content;}
  4. f = Open (' db ', ' a ') # append mode, {readable; not exist then create; only append content;}
  5. f = Open (' db ', ' x ') # file exists, error is present, no content is created and written
  6. "+" means that you can read and write to a file:
  7. f = Open (' db ', ' r+ ') # can read and write files, {readable; writable; can append}
  8. f = Open (' db ', ' w+ ') # write Read.
  9. f = Open (' db ', ' A + ') # with A.
  10. "U" means that \ r \ n can be automatically converted to \ n (in conjunction with R or r+ Mode) when reading
  11. f = Open (' db ', ' RU ')
  12. f = Open (' db ', ' R+u ')
  13. "b" means processing binary files (such as FTP upload ISO image, linux ignore, Windows processing binaries need to be labeled)
  14. f = Open (' db ', ' RB ') # binary Read-only
  15. f = Open (' db ', ' WB ') # Binary write only
  16. f = Open (' db ', ' ab ') # binary Append
  17. f = Open (' db ', ' r ')
  18. data = F.read ()
  19. Print (data,type (data))
  20. F.close ()
    • 2. Operating files
    1. f = Open (' db ', ' r+ ', encoding= "utf-8")
    2. data = F.read (1) # If open mode is no b, then read, reads by character
    3. Print (f.tell ()) # Tell where the current pointer is (in bytes)
    4. F.seek (f.tell ()) # Adjustment current pointing to your position (bytes)
    5. F.write ("777") # Current pointer position start overwrite
    6. Print (data) # printout
    7. F.close () # Close the current file
    8. Through the Source view function
    9. Read () # no arguments, reads all; parameter, b byte, no B by character
    10. Tell () # Gets the current pointer position (in bytes)
    11. Seek () # pointer jumps to the specified position (bytes)
    12. Write () # writes data, b: bytes, no B: character
    13. Close () # closing file
    14. Fileno () # File descriptor
    15. Flush () # flush File Internal buffer
    16. ReadLine () # Read Only one row
    17. Truncate () # intercept, empty after pointer position
    • 3.for Loop File Object
    1. f = Open ("")
    2. For line in F:
    3. Print (line)
    • 4. File Modification
    1. # db file with "xuliangwei" string
    2. f = Open ("db", "r", encoding= "utf-8")
    3. f_new = open ("db.bak", "w", encoding= "utf-8")
    4. For line in F:
    5. If "xuliangwei" in Line:
    6. line = Line.replace ("xuliangwei", "xuliangwei.com")
    7. F_new.write (line)
    8. F.close ()
    9. F_new.close ()
    • 5. Close the file
    1. F.close () #直接close文件
    2. Avoid opening files after forgetting to close, unified through the management context, namely:
    3. With open (' db1 ', ' r ') as f1, open ("db2", ' W ') as F2:
    4. Pass
1.4 Python character encoding conversion

Asiica does not support Chinese
Utf-8 a man: three bytes
GBK a man: two bytes

The default character encoding in Python3 is Utf-8

    1. #!/usr/bin/env python
    2. name = ' Li Zhong '
    3. Print (name.encode (' UTF-8 ')) # to UTF-8 encoding
    4. Print (name.encode (' GBK ')) # to GBK encoding
    5. Print (name.encode (' ASCII ')) # to ASCII encoding

The default character encoding in python2.x is Unicode

Python (iii)

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.