Python Road, Day2-python Foundation 2

Source: Internet
Author: User
Tags readable



The content of this section


    1. list, tuple operations
    2. String manipulation
    3. Dictionary operations
    4. Collection operations
    5. File operations
    6. Character encoding and transcoding
1. List, tuple operations


The list is one of the most commonly used data types in the future, and the list allows for the most convenient storage, modification and other operations of the data.



Definition List


names =[‘Alex‘,"Tenglan",‘Eric‘]


To access the elements in the list by subscript, the index is counted starting at 0


8 >>> names[0]‘Alex‘>>> names[2]‘Eric‘>>> names[-1]‘Eric‘>>> names[-2] #还可以倒着取‘Tenglan‘


Slices: Fetching multiple elements  


View Code


Additional


View Code


Insert


View Code


Modify


View Code


Delete


View Code


Extended


View Code


Copy


View Code


Is copy really that simple? Then I'll tell you a fart ...



Statistics


View Code


Sort & Flip


View Code


Get subscript


View CodeMeta-group


Tuples are actually similar to the list, but also to save a group of numbers, it is not once created, it can not be modified, so it is called a read-only list



Grammar


names =("alex","jack","eric")


It has only 2 methods, one is count, the other is index, complete.


Program Exercises


Please close your eyes and write the following procedure.



Program: Shopping Cart Program



Demand:


    1. After you start the program, let the user enter the payroll, and then print the list of items
    2. Allow users to purchase items based on their product number
    3. After the user selects the product, checks whether the balance is enough, enough on the direct debit, enough to remind
    4. You can exit at any time to print the purchased goods and balances when exiting




2. String Manipulation


Features: cannot be modified


name.capitalize () initials
name.casefold () uppercase and lowercase
name.center (50, "-") output '--------------------- Alex Li --------------- ------- '
name.count (‘lex’) counts the number of occurrences of lex
name.encode () encodes a string into bytes
name.endswith ("Li") determines whether the string ends with Li
 "Alex \ tLi" .expandtabs (10) outputs ‘Alex Li’, which converts \ t into how many spaces
 name.find (‘A’) finds A, finds its index, returns -1 if not found

format:
    >>> msg = "my name is {}, and age is {}"
    >>> msg.format ("alex", 22)
    ‘My name is alex, and age is 22’
    >>> msg = "my name is {1}, and age is {0}"
    >>> msg.format ("alex", 22)
    ‘My name is 22, and age is alex’
    >>> msg = "my name is {name}, and age is {age}"
    >>> msg.format (age = 22, name = "ale")
    ‘My name is ale, and age is 22’
format_map
    >>> msg.format_map ({‘name‘: ‘alex’, ‘age’: 22})
    ‘My name is alex, and age is 22’


msg.index (‘a’) returns the index of the string where a is located
‘9aA’.isalnum () True

‘9’.isdigit () is an integer
name.isnumeric
name.isprintable
name.isspace
name.istitle
name.isupper
 "|" .join ([‘alex‘, ’jack’, ‘rain’])
‘Alex | jack | rain’


maketrans
    >>> intab = "aeiou" #This is the string having actual characters.
    >>> outtab = "12345" #This is the string having corresponding mapping character
    >>> trantab = str.maketrans (intab, outtab)
    >>>
    >>> str = "this is string example .... wow !!!"
    >>> str.translate (trantab)
    ‘Th3s 3s str3ng 2x1mpl2 .... w4w !!!’

 msg.partition (‘is’) output (‘my name‘, ‘is’, ‘{name}, and age is {age}‘)

 >>> "alex li, chinese name is lijie" .replace ("li", "LI", 1)
     ‘Alex LI, chinese name is lijie’

 msg.swapcase case exchange


 >>> msg.zfill (40)
‘00000my name is {name}, and age is {age}’



>>> n4.ljust (40, "-")
‘Hello 2orld -----------------------------’
>>> n4.rjust (40, "-")
‘----------------------------- Hello 2orld’


>>> b = "ddefdsdff_haha"
>>> b.isidentifier () #Check if a string can be used as an identifier, that is, whether it meets the variable naming rules
True







3. Dictionary operation


A key-value data type, used as a dictionary of our school, to check the details of the corresponding page by strokes and letters.



Grammar:


info = {
    ‘stu1101‘: "TengLan Wu",
    ‘stu1102‘: "LongZe Luola",
    ‘stu1103‘: "XiaoZe Maliya",
}


Features of the dictionary:


    • Dict is disordered.
    • Key must be unique and so is inherently heavy


Increase


View Code


Modify


View Code


Delete


View Code


Find


View Code


Multi-level dictionary nesting and manipulation


View Code





Other poses


View Code


Cyclic dict


#method 1
for key in info:
     print (key, info [key])

#Method 2
for k, v in info.items (): #It will first convert the dict into a list.
     print (k, v)


Program Exercises



Program: Level Three Menu



Requirements:


    1. Print provincial, city, and county level three menus
    2. Can return to the upper level
    3. Can exit the program at any time




Three-year menu literary Youth Edition







4. Collection Operations


A collection is an unordered, non-repeating combination of data, and its main functions are as follows:


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


Common operations


View Code




5. File Operation


Procedure for file operation


    1. Open the file, get the file handle and assign a value to a variable
    2. Manipulating a file with a handle
    3. Close File


The existing files are as follows


+ View Code


Basic operations


f = open ('lyrics') #Open the file first_line = f.readline () print (' first line: ', first_line) #Read a line print (' I am the separator'.center (50, '-')) data = f.read () # Read all the rest, do not use print (data) when the file is large #print the file f.close () #close the file


The mode of opening the file is:


    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"


"+" means you can read and write a file at the same time


    • r+, can read and write files. "readable; writable; can be added"
    • w+, write and read
    • A +, with a


"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading


    • RU
    • R+u


"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)


    • Rb
    • Wb
    • Ab


Other syntax


def close (self): # real signature unknown; restored from __doc__
        "" "
        Close the file.
        
        A closed file cannot be used for further I / O operations. Close () may be
        called more than once without error.
        "" "
        pass

    def fileno (self, * args, ** kwargs): # real signature unknown
        "" "Return the underlying file descriptor (an integer)." ""
        pass

    def isatty (self, * args, ** kwargs): # real signature unknown
        "" "True if the file is connected to a TTY device." ""
        pass

    def read (self, size = -1): # known case of _io.FileIO.read
        "" "
        Note that you may not be able to read it all
        Read at most size bytes, returned as bytes.
        
        Only makes one system call, so less data may be returned than requested.
        In non-blocking mode, returns None if no data is available.
        Return an empty bytes object at EOF.
        "" "
        return ""

    def readable (self, * args, ** kwargs): # real signature unknown
        "" "True if file was opened in a read mode." ""
        pass

    def readall (self, * args, ** kwargs): # real signature unknown
        "" "
        Read all data from the file, returned as bytes.
        
        In non-blocking mode, returns as much as is immediately available,
        or None if no data is available. Return an empty bytes object at EOF.
        "" "
        pass

    def readinto (self): # real signature unknown; restored from __doc__
        "" "Same as RawIOBase.readinto ()." ""
        pass # Don't use it, no one knows why it is used

    def seek (self, * args, ** kwargs): # real signature unknown
        "" "
        Move to new file position and return the file position.
        
        Argument offset is a byte count. Optional argument whence defaults to
        SEEK_SET or 0 (offset from start of file, offset should be> = 0); other values
        are SEEK_CUR or 1 (move relative to current position, positive or negative),
        and SEEK_END or 2 (move relative to end of file, usually negative, although
        many platforms allow seeking beyond the end of a file).
        
        Note that not all file objects are seekable.
        "" "
        pass

    def seekable (self, * args, ** kwargs): # real signature unknown
        "" "True if file supports random-access." ""
        pass

    def tell (self, * args, ** kwargs): # real signature unknown
        "" "
        Current file position.
        
        Can raise OSError for non seekable files.
        "" "
        pass

    def truncate (self, * args, ** kwargs): # real signature unknown
        "" "
        Truncate the file to at most size bytes and return the truncated size.
        
        Size defaults to the current file position, as returned by tell ().
        The current file position is changed to the value of size.
        "" "
        pass

    def writable (self, * args, ** kwargs): # real signature unknown
        "" "True if file was opened in a write mode." ""
        pass

    def write (self, * args, ** kwargs): # real signature unknown
        "" "
        Write bytes b to file, return number written.
        
        Only makes one system call, so not all of the data may be written.
        The number of bytes actually written is returned. In non-blocking mode,
        returns None if the write would block.
        "" "
        pass


With statement



To avoid forgetting to close a file after opening it, you can manage the context by:


with open(‘log‘,‘r‘) as f:        ...


This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.



After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:


with open(‘log1‘) as obj1, open(‘log2‘) as obj2:    pass

 





Program Exercises



Program 1: Implement a simple shell sed replacement function



Program 2: Modify the Haproxy configuration file



Demand:


Demand Original configuration file




6. Character encoding and transcoding


Detailed article:



Http://www.cnblogs.com/yuanchenqi/articles/5956943.html



Http://www.diveintopython3.net/strings.html


Need to know:

1. In Python2 the default encoding is ASCII, the default is Unicode in Python3

2.unicode is divided into utf-32 (4 bytes), utf-16 (accounting for two bytes), Utf-8 (1-4 bytes), so utf-16 is now the most commonly used Unicode version, but in the file is still utf-8, because the UTF8 save space

3. Encode in Py3, while transcoding will also change the string to bytes type, decode decoding will also turn bytes back to string






Only available for Py2





In Python2In Python3








7. Built-in functions


Category: The path to automated python development


Python Road, Day2-python Foundation 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.