General Decoration Device
# (@+ function name), you need to remember the key two points:
#功能:
#1, automatically executes the outer function, and passes the function name F1 below as a parameter
#2, re-assigns the return value of the outer function to F1
# #装饰器必备
# # # # #第一: function names and execution functions # # #
# def foo (): #创建函数
# print (' Hello ') #函数体
# foo #表示是函数名, substituting the entire function
# foo () #表示执行f00函数
# # Output: Hello
# # # # #第二: function redefined # # #
# def foo ():
# print ("Foo1")
#
# foo = lambda:print ("Foo2") #lambda表达式, no parameters
#
# foo () #执行下面的lambda表达式, instead of the original Foo function, the Foo function has been redefined
Common Module Time Module time.time ()
Import timeimport datetimeprint (Time.time ()) # Returns the timestamp of the current time
Time.ctime ()
Print (Time.ctime ()) # Converts a timestamp to a string format wed 17 11:41:27 2016, the default is the timestamp of the current system time print (Time.ctime (time.time ()-3600)) # CTime can receive a timestamp as a parameter, returning the string form of that timestamp Wed 17 10:43:04 2016
Time.gtime ()
Print (Time.gmtime ()) # converts timestamp to struct_time format, default is current system timestamp print (Time.gmtime (time.time ()-3600))
Time.localtime ()
Print (Time.localtime ()) # also converts the timestamp to struct_time, except that it shows the local time, gmtime the standard Time (Galini time)
Time.mktime ()
Print (Time.mktime (Time.localtime ())) # Convert Struct_time time format to timestamp
Time.strftime ()
Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) # Converts the struct_time time format to a custom string format
Time.trptime ()
Print (Time.strptime ("2016-02-17", "%y-%m-%d")) # In contrast to Trftime, convert string format to struct_time format
Time.asctime ()
Print (Time.asctime (Time.localtime ())) # converts struct_time into string form
DateTime module
- Datetime.date: A class that represents a date. Common attributes are year, month, day
- Datetime.time: A class that represents time. Common properties are hour, minute, second, microsecond
- Datetime.datetime: Represents the date time
- Datetime.timedelta: Represents a time interval, that is, the length between two points in time
Datetime.date.today ()
Print (Datetime.date.today ()) # Returns the string form of the current date 2016-02-17
Datetime.date.fromtimestamp ()
Print (Datetime.date.fromtimestamp (time.time ()-3600 * 24)) # Converts a timestamp into a date string form 2016-02-16
Datetime.datetime.now ()
Print (Datetime.datetime.now ()) # Returns the time of the string form 2016-02-17 13:53:30.719803print (Datetime.datetime.now (). Timetuple ()) # Convert to Struct_time format
Datetime.timedelta ()
Datetime.timedelta () Returns a time interval object, often combined with datetime.datetime.now () to compute time
Print (Datetime.datetime.now ()-Datetime.timedelta (days = 2))
Random module
The random module is primarily used to generate
Random ()
Generate a random number of floating-point types greater than 0 and less than 1
Print (Random.random ()) #生成大于0小于1的浮点类型随机数
Serialization of
Two modules for serialization in Python
- JSON is used to convert between "string" and "Python Basic data Types"
- Pickle for "Python-specific type" and "Python basic data type" to convert between
The JSON module provides four functions: dumps, dump, loads, load
The Pickle module provides four functions: dumps, dump, loads, load
OS Module
Provides an interface to invoke the operating system
>>> ImportOs>>> os.getcwd () # Gets the current working directory, like the linux pwd command '/data/python/day5 ' >>> os.chdir (' ... ') # into a directory, Linux-like CD commands >>>OS.GETCWD () '/data/python ' >>> os.curdir # Get current directory '. ' >>> Os.pardir # Gets the parent directory of the current directory ' ... ' >>> os.chdir (' Day5 ') >>>OS.GETCWD () '/data/python/day5 ' >>> os.makedirs (' Testdir1/testdir2 ') # recursively create directories equivalent to MKDIR-P commands >>> Os.makedirs (' Test_dir1/test_dir2 ') # Recursive create directory equivalent to mkdir-p command >>> os.listdir ('. ') # Show directories under All files equivalent to Linux ls-a[' test _dir1 ']>>> os.removedirs (' Test_dir1/test_dir2 ') # Delete the multilevel (recursive) directory, note that the directory must be empty, if the directory is empty, and recursively to the top and directory, if also empty also delete >>> Os.mkdir (' Test2 ') # Create directory, equivalent to mkdir>>> os.rmdir (' test2 ') # Delete directory, equivalent to rm>>> f = open (' Test.txt ', ' W ') >>> f.write (' Testline ') 8>>>F.close () >>>Os.listdir () [' Testdir2 ', ' test.txt ', ' Testdir1 ']>>> os.rename (' test.txt ', ' new_test.txt ') #重命名 >>> os.stat ('. ') # Displays the status of the directory or file, including permissions Os.stat_result ( st_mode=16877, st_ino=786731, st_dev=64784, st_nlink=4, St_uid=0, St_gid=0, st_size=4096, st_atime=1455695375, St_ mtime=1455696066, st_ctime=1455696066) >>> os.sep # Get file separator, Linux for/,windows \ '/' >>> Os.name # return platform name, Linux for Posix,win nt ' POSIX ' >> > Os.linesep # Returns the system newline character, win under \ r \ n ' \ nthe ' >>> os.pathsep # Returns the string used to split the file path, under Vin; ': ' >>> os.system (' ls ') # Execute Shell commandTestdir1 testdir20>>> Os.environ # Get system environment variable environ ({' USER ': ' Root ', ' PATH ': '/usr/local/sbin:/usr/local/bin :/usr/sbin:/usr/bin:/sbin:/bin ', ' SHELL ': '/bin/bash ', ' HOME ': '/root ', ' shlvl ': ' 1 ', ' histtimeformat ': '%... Omit n More good ...>>> os.path.abspath ('. ') # Returns the absolute path to the directory '/data/python/day5 ' >>> os.path.split ('/data/python/ Day5 ') # divides path into directories and files, Ganso returns ('/data/python ', ' day5 ') >>> os.path.dirname ('/data/python/day5 ') # Returns path is also the first element of Split '/data/python ' >>> Os.path.basename ('/data/python/day5 ') # returns the filename is also the first element of Split ' Day5 ' >>> os.path.exists ('/data/python/day5 ') # Determine if a directory or file existstrue>>> os.path.isabs ('/data/python/day5 ') # Determines if it is an absolute directory, regardless of whether it exists, and plainly that the string conforms to the absolute path of the specification returns Truetrue> >> os.path.isabs (' day5 ') false>>> os.path.isabs ('/data/python/day6 ') # true>>> Os.path.isfile ('/data/python/day5 ') # Determines if the file is false>>> os.path.isdir ('/data/python/day5 ') # to determine if it is a directory True>>> os.path.isdir ('/data/python/day6 ') false>>> os.path.join ('/data/python/day6 ', ' Test ' # combined directory '/data/python/day6/test ' >>> os.path.getatime ('/data/python/day5 ') # Returns the last access time for a file or directory 1455695375.9394312>>> os.path.getmtime ('/data/python/day5 ') # Returns the last modified time for a file or directory 1455696066.0034554>>> os.path.getctime ('/data/python/day5 ') # Returns the creation time of a file or directory 1455696066.0034554
Regular expressions
Strings are the most data structure involved in programming, and the need to manipulate strings is almost ubiquitous. For example, to determine whether a string is a legitimate email address, although it can be programmed to extract the substring before and after, and then judge whether it is a word and domain name, but this is not only cumbersome, and the code is difficult to reuse.
A regular expression is a powerful weapon used to match strings. Its design idea is to use a descriptive language to define a rule for a string, and any string that conforms to the rule, we think it "matches", otherwise the string is illegal. The following diagram shows the process of using regular expression matching Python's re module
Python provides support for regular expressions through the RE module. The general step for using re is to compile the string form of the regular expression into a pattern instance, then use the pattern instance to process the text and get the matching result (a match instance), and finally use the match instance to get the information and do other things.
Import Re # compiles the regular expression into a pattern object pattern = Re.compile (r ' Hello ') # matches the text using pattern to get the match result, which will return Nonematch = Pattern.match (' Hello world! ' if match: # use Match to get Group Info print match.group ()
Re modules common methods Re.compile (strpattern[, flag]) parameters: Strpattern: Regular Expressions flag: Match mode, selectable values are re. I (re. IGNORECASE): Ignore case (full notation within parentheses) m (MULTILINE): Multiline mode, change ' ^ ' and ' $ ' ' Behavior (see) s (dotall): Point any matching pattern, change '. ' Behavior l (locale): Make a predetermined character class \w \w \b \b \s \s depending on the current locale  &NBS p; u (Unicode): Make a predetermined character class \w \w \b \b \s \s \d \d Depending on the character attributes of the UNICODE definition   &NB Sp x (VERBOSE): Verbose mode. In this mode, the regular expression can be multiple lines, ignore whitespace characters, and can be added to comments. Return value: The Pattern object is a compiled regular expression that can be matched by a series of methods provided by pattern to find The following method can be either an instance method of the Pattern object or a method of the re module, with a slightly different syntax match (string[, pos[, Endpos]) | Re.match (pattern, string[, flags]) This method will try from the POS subscript of stringMatch pattern; Returns a Match object if the pattern is still matched at the end, or none if pattern does not match during the match, or if the match does not end with Endpos. The default values for pos and Endpos are 0 and Len (string), Re.match () cannot specify both parameters, and the parameter flags specify a matching pattern when compiling pattern. Note: This method is not an exact match. If the string has any remaining characters at the end of the pattern, it is still considered successful. If you want an exact match, you can add the boundary match ' $ ' at the end of the expression. Parameters: string: string to match pos: Match start subscript Endpos: Matching end subscript pattern: Regular expression flags: Match mode return value: If the match is returned successfully, the Nonesearch is returned ( string[, pos[, Endpos]) | Re.search (pattern, string[, flags]) This method is used to find substrings in a string that can match a success. Attempts to match the pattern from the POS subscript of string, returns a match object if the pattern ends with a match, and tries to match the POS after 1 if it does not match, and returns none until Pos=endpos is still not matched. The default values for POS and Endpos are 0 and Len (string), and Re.search () cannot specify both parameters, and the parameter flags specify a matching pattern when compiling pattern. Parameters: Same match return value: Same as match Let's look at the difference between the two methods in one example
>>> Import re>>> s = ' Hello World ' >>> print (Re.match (' Ello ', s)) none>>> Print (Re.search (' Ello ', s)) <_sre. Sre_match object; Span= (1, 5), match= ' Ello ' > Description: You can see that the MACTH only matches the beginning, the beginning does not match, it does not match to, search can be from the middle, as long as there can match to even if matching findall (string[, POS [, Endpos]]) | Re.findall (pattern, string[, flags]) searches for a string, returning all matching substrings in a list. A bit like the extension of search, put all matching substrings into a list parameter: Same match return value: All matched substrings, no matches return empty list >>> import re >>> s = ' One1two2three3four4 ' >>> re.findall (' \d+ ', s) [' 1 ', ' 2 ', ' 3 ', ' 4 ']
Split (string[, Maxsplit]) | Re.split (Pattern, string[, Maxsplit]): Splits the string according to the matching substring, returning the split list parameter: string: The string to be split pattern: regular Expression Maxsplit : Maximum number of splits return value: Split List instance
>>> Import re >>> s = ' one1two2three3four4 ' >>> re.split (' \d+ ', s) [' One ', ' one ', ' ' Three ', ' four ', ']
Sub (repl, string[, Count]) | Re.sub (Pattern, REPL, string[, Count]) uses REPL to replace each substring parameter that matches in string: Repl: Replacement string or method, here's how to say this method, the method receives the Macth object, the return value of the method as The replaced string, in other words, the processed string. String: Pattern of strings to be replaced: regular expression count: Number of instances of substitution: For Repl is a method of the case, just this job to use, to replace a number of it is difficult to cross the case. Suppose we have a arithmetic expression '--(1.1+1+1-( -1)-(1+1+ (1+1+2.2))) +-----111+--++--3-+++++++---+---1+4+4/2+ (1+3) *4.1+ (2-1.1) *2/2*3 ', followed by an odd number of minus signs equal to the principle of being otherwise negative, we can
if __name__ = = ' __main__ ': import re s = '--(1.1+1+1-( -1)-(1+1+ (1+1+2.2))) +-----111+--++--3-+++++++- --+---1+4+4/2+ (1+3) *4.1+ (2-1.1) *2/2*3 ' def replace_sign (expression): ' replaces multiple consecutive-I-sign issues, such as +----- , followed by an odd number of negative signs equal to the principle of being otherwise negative :p Aram expression: expression, including parentheses: return: Returns the processed expression ' def re_sign ( m): if m: if M.group (). Count ('-')%2 = = 1: Return '-' else: return '+ ' else: return ' E Xpression = Re.sub (' [\+\-]{2,} ', re_sign, expression) return expression s = replace_sign (s) print (s)
Execution results
24 + (1.1+1+1-(-1)-(1+1+ (1+1+2.2))) -111+3-1+4+4/2+ (1+3) *4.1+ (2-1.1) *2/2*3
Python Basics (3)