In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this "Python time module time () and datetime () how to use" article, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Python time module time () and datetime () how to use" article.
Important functions in time module time () and datetime () time () module
Time format conversion of time () module
Time () module time conversion
Timestamp the second after January 1, 1970, that is: time.time ()
The formatted string 2014-11-11 11:11, that is: time.strftime ('% YMMI% MMI% d')
The structured time tuple contains: year, day, week, etc. Time.struct_time is: time.localtime ()
Import timeprint (time.time ()) # timestamp: 1511166937.2178104print (time.strftime ('% YMY% MMI% d')) # formatted string: 2017-11-20print (time.localtime ()) # structured time (tuple): (tm_year=2017) Tm_mon=11...) print (time.gmtime ()) # converts time to tuple format in utc format: (tm_year=2017, tm_mon=11...) # 1. Convert structured time to timestamp: 1511167004.0print (time.mktime (time.localtime () # 2. Convert the lattice string time into a structured time tuple: (tm_year=2017, tm_mon=11...) print (time.strptime ('2014-11-11,'% Ymure% mmi% d')) # 3. The structured time (tuple) is converted to a string time: 2017-11-20print (time.strftime ('% YMY% mMel% dashes, time.localtime () # default current time # 4. Convert structured time (tuple) into English string time: Mon Nov 20 16:51:28 2017print (time.asctime (time.localtime () # 5. Time stamp converted to English string time: Mon Nov 20 16:51:28 2017print (time.ctime (time.time () ctime and asctime difference
1) ctime passes in a timestamp timed in seconds to convert it into a formatting time
2) asctime passes in time tuples to convert to formatting time
Import timet1 = time.time () print (T1) # 1483495728.4734166print (time.ctime (T1)) # Wed Jan 4 10:08:48 2017t2 = time.localtime () print (T2) # time.struct_time (tm_year=2017, tm_mon=1, tm_mday=4, tm_hour=10 Print (time.asctime (T2)) # Wed Jan 4 10:08:48 2017datetime acquires time import datetime#1, datetime.datetime acquires current time print (datetime.datetime.now ()) # 2, time print (datetime.datetime.now () + datetime.timedelta (+ 3)) # 3, time print (datetime.datetime.now () + datetime.timedelta (- 3)) # 4, Get the time print (datetime.datetime.now () + datetime.timedelta (hours=3)) # 5 after three hours Get the time three minutes ago print (datetime.datetime.now () + datetime.timedelta (minutes =-3)) import datetimeprint (datetime.datetime.now ()) # 2017-08-18 11:25:52.618873print (datetime.datetime.now (). Date ()) # 2017-08-18print (datetime.datetime.now (). Strftime ("% Ymurt%) MMI% d% H-%M-%S ") # 2017-08-18 11-25-52datetime time conversion # 1, Conversion of datetime object to str # datetime.datetime.now (). Strftime ("% Y-%m-%d% H:%M:%S") '2018-03-09 10 datetime.datetime.now 08 datetime.datetime.now 50 datetime.datetime.strptime (' 2016-02-22') "% Y-%m-%d") datetime.datetime (2016, 2, 22, 0, 0) # 2, datetime object to time tuple # datetime.datetime.now (). Timetuple () time.struct_time (tm_year=2018, tm_mon=3, tm_mday=9,#3, timestamp converted to datetime object # datetime.datetime.fromtimestamp (1520561646.8906238) datetime.datetime (2018, 3, 9, 10, 14, 6) 890624) conversion between local time and utc time # conversion between local time and utc time import timeimport datetimedef utc2local (utc_st):''function: replace UTC time with local time: param utc_st: pass in utc time (datatime object): return: return local time datetime object' 'now_stamp = time.time () local_time = datetime. Datetime.fromtimestamp (now_stamp) utc_time = datetime.datetime.utcfromtimestamp (now_stamp) offset = local_time-utc_time local_st = utc_st + offset return local_stdef local2utc (local_st):''function: convert local time to UTC time: param local_st: local time passed in (datatime object): return: utc time datetime object''is returned Time_struct = time.mktime (local_st.timetuple ()) utc_st = datetime.datetime.utcfromtimestamp (time_struct) return utc_stutc_time = datetime.datetime.utcfromtimestamp (time.time ()) # utc_time = datetime.datetime (2018 5, 6, 5, 57, 9, 511870) # 8 hours later than Beijing time local_time = datetime.datetime.now () # local_time = datetime.datetime (2018, 5, 6, 13, 59, 27 120771) # Beijing Local time utc_to_local = utc2local (utc_time) local_to_utc = local2utc (local_time) print utc_to_local # 2018-05-06 1402utc_time 30.650270 has been converted to Beijing Local time print local_to_utc # 2018-05-06 06:02:30 converted to Beijing Local time timezone time and Local time conversion # Conversion between timezone time and local time of django from django.utils import timezonefrom datetime import datetimeutc_time = timezone.now () local_time = datetime.now () # 1, Utc time is replaced by local time utc_to_local = timezone.localtime (timezone.now ()) # 2, local time utc time local_to_utc = timezone.make_aware (datetime.now ()) Timezone.get_current_timezone () Python calculates the number of days between two dates import datetimed1 = datetime.datetime (2018 Magazine 31) # first date D2 = datetime.datetime (20119 Magazine 2) # second date interval = D2-D1 # the gap between two dates print (interval.days) # specific number of days 2, random () module random () module common function
Examples of common functions in random: import random# ⒈ random integers: print (random.randint (0,101,2)) # randomly select integers print (random.randrange (0,101,2)) # randomly select even numbers # ⒉ random floating point numbers: print (random.random ()) # 0.972654134347print (random.uniform (1) ) # 4.1470981377 random ⒊ characters: print (random.choice ('abcdefg')) # cprint (random.sample (' abcdefghij',3)) # ['jacks,' fags,'c'] uses random to implement four-digit CAPTCHA code 1. Use for Loop implementation # use for Loop to implement import randomcheckcode =''for i in range (4): current = random.randrange (0Magne4) if current = = I: tmp = chr (random.randint (65je 90)) # 65je 90 means all uppercase letters else: tmp = random.randint (0je 9) checkcode + = str (tmp) print (checkcode) # run result: 851K2. Use random.sample to implement import randomimport stringstr_source = string.ascii_letters + string.digitsstr_list = random.sample (str_source,7) # ['iTunes,' Qcodes, 'Utility,' ubiquitous, 'Aids,' 0' '9'] print (str_list) str_final =' .join (str_list) # iQUuA09print (str_final) # run result: jkFU2Ed III. Os module os module common methods import os#1 current working directory That is, the directory path where the current python script works print (os.getcwd ()) # C:\ Users\ admin\ PycharmProjects\ S14\ Day5\ test4#2 current script working directory Equivalent to cdos.chdir under shell ("C:\\ Users\\ admin\\ PycharmProjects\\ S14") os.chdir (r "C:\ Users\ admin\ PycharmProjects\ S14") print (os.getcwd ()) # C:\ Users\ admin\ PycharmProjects\ s14room3 returns the current directory: ('.') print (os.curdir) # ('.) # 4 get the string name of the parent directory of the current directory: ('.') Print (os.pardir) # ('..') # 5 can generate a multi-tier recursive directory os.makedirs (raster C:\ aaa\ bbb') # you can find that a folder / aaa/bbb#6 is created on disk C if the directory is empty Delete and recursively go to the directory one level above, or delete it if it is also empty, and so on os.removedirs (ritual C:\ aaa\ bbb') # Delete all empty directories # 7 to generate a single-level directory Equivalent to mkdir dirnameos.mkdir (raster C:\ bbb') # in shell can only create a single directory # 8 Delete a single-level empty directory, if the directory is not empty, it cannot be deleted, an error is reported Equivalent to rmdirdirnameos.rmdir (ritual C:\ aaa') # in shell only deletes an empty directory specified # 9 lists all files and subdirectories in the specified directory, including hidden files And print print as a list (os.listdir (r "C:\ Users\ admin\ PycharmProjects\ s14") # 10 Delete a file os.remove (raster C:\ bbb\ test.txt') # specify delete test.txt file # 11 rename file / directory os.rename (ritual C:\ bbb\ test.txt' Raster C:\ bbb\ test00.bak') # 12 get file / directory information print (os.stat (ritual C:\ bbb\ test.txt')) # 13 output operating system-specific path separator "\" under win, "/" print (os.sep) #\ # 14 under Linux to output the line Terminator used by the current platform, "\ r\ n" under win, and "\ n" print (os.linesep) # 15 to output the string print (os.pathsep) # used to split the file path (semicolon) # 16 output string indicates that the platform is currently being used. Win- > 'nt'; Linux- >' posix'print (os.name) # nt#17 runs the shell command, which directly displays os.system ("bash command") # 18 to get the system environment variable print (os.environ) # environ ({'OS':' Windows_NT', 'PUBLIC':). . # 19 returns the absolute path to the path normalization print (os.path.abspath (ringing Clax _ peg _ bbmax _ test.txt')) # C:\ bbb\ test.txt#20 splits the path into directories and file name binaries and returns print (os.path.split (ringing Clax _) _ In fact, the first element of os.path.split (path), print (os.path.dirname (ringing Claxpool hand bbbhand ccc')) # C:/bbb#22 returns the last filename of path. If the path ends with / or\, a null value is returned. That is, the second element of os.path.split (path), print (os.path.basename (ringing Cpurl / BBG / BBG / BCC / / DDd') # ddd#23 returns True if path exists. If the path does not exist, return Falseprint (os.path.exists (ringing path PycharmProjects bbbb test4') # True#24 if the path is absolute, return True# Trueprint (os.path.isabs (r "C:\ Users\ admin\ PycharmProjects\ S14\ Day5\ test4") # 25 return True if path is an existing file. Otherwise, it will return Falseprint (os.path.isfile (ringing Corel _ peg _ BBG _ BBG _ CCC _ Unip _ test2.txt') # True#26 if path is an existing directory, then return True. Otherwise, return Falseprint (os.path.isdir (ringing CTrue#28)) # True#28 returns the last access time print of the file or directory pointed to by path (os.path.getatime (ringing Corel hand bblash ccxt')) # 1483509254.964714329 returns the last modification time of the file or directory pointed to by path (os.path.getmtime (r'C:/bbb) / ccc/test2.txt') # 1483510068.74647830No matter whether it is linux or windows Splice the file path put_filename ='% s% self.home,os. Path.sep, filename) # C:\ Users\ admin\ PycharmProjects\ s14\ day10select version FTP\ homeos command to create a folder: C:/aaa/bbb/ccc/ddd and write to the file file1.txtimport osos.makedirs ('CJV peg Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalexabaleandroid (exist_ok=True), f_path = os.path.join (path). 'file.txt') with open (' are you path') Dynamically add the absolute path of other directories to the environment variable of pyhton import os,sysprint (os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__))) BASE_DIR = os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__))) sys.path.append (BASE_DIR) # Code explanation: # to import functions from other directories In fact, the absolute path of other directories is dynamically added to the environment variable of pyhton. In this way, the python interpreter can find the imported module at run time without reporting an error: # and then call the sys module sys.path.append (BASE_DIR) to add this path to the python environment variable os.popen to get the script execution result 1.data.pydata = {'name':'aaa'} import jsonprint json.dumps (data) 2.getroomdata.python! / usr/bin/env python#-*-coding: utf-8-*-import os Jsonret = os.popen ('python data.py') data = ret.read () .strip () ret.close () data = json.loads (data) print data # {' name':'aaa'} IV, sys module 1, sys basic method sys.argv returns the parameter sys.exit (n) passed in to execute the script to exit the program Exit (0) sys.version gets the version information of the Python interpreter on normal exit. Sys.maxint 's maximum int value sys.path returns the search path of the module. Use the value of the PYTHONPATH environment variable sys.platform to return the operating system platform name sys.stdout.write ('please:') val = sys.stdin.readline () [:-1] 2, and use sys to return the running script parameters import sys# C:\ Users\ tom\ PycharmProjects\ s14Review\ day01 > python test01.py 1 2 3print (sys.argv) # print all parameters [' test01.py','1' '2percent,' 3'] print (sys.argv [1:]) # get all the parameters after index 1 ['1percent,' 2percent,'3'] tarfile is used to archive folders into .tar files tarfile uses import tarfile# to archive folders Day1 and Day2 into your.rar and in the archive folder Day1 and Day2 become compressed files tar = tarfile.open ('your.tar') of bbs2.zip and ccdb.zip, respectively 'w') tar.add (ritual C:\ Users\ admin\ PycharmProjects\ S14\ Day1', arcname='bbs2.zip') tar.add (rascal C:\ Users\ admin\ PycharmProjects\ S14\ Day2', arcname='cmdb.zip') tar.close () # decompress the archive file your.tar and decompress the bbs2.zip and cmdb.zip files instead of changing into the original folder tar = tarfile.open (' your.tar' 'r') tar.extractall () # can set the decompression address tar.close () shutil to create a compressed package, copy, move files
Note: shutil handles compressed packages by calling ZipFile and TarFile modules: shutil creates compressed packages and returns file paths (such as zip, tar), and can copy files and move files
Shutil uses import shutil#1 copyfileobj () to copy the contents of the file test11.txt into the test22.txt file, F1 = open ("test11.txt", encoding= "utf-8") f2 = open ("test22.txt", 'wicked penciling encoding = "utf-8") shutil.copyfileobj (f1Magnef2) # 2 copyfile () directly specify the file name to copy shutil.copyfile ("test11.txt",' test33.txt') # 3 shutil.copymode (src, dst) only copy permission. Content, groups, and users remain unchanged # 4 shutil.copystat (src, dst) copy status information, including: mode bits, atime, mtime, flagsshutil.copystat ('test11.txt','test44.txt') # 5 Recursive to copy all directories and files in the directory, where test_dir is a folder Contains multi-level folders and files shutil.copytree ("test_dir", "new_test_dir") # 6 recursively deletes all directories and files in the directory, where test_dir is a folder Contains multi-level folders and files shutil.rmtree ("test_dir") # 7 shutil.move (src, dst) recursively to move files shutil.move ('os_test.py',r'C:\\') # 8 shutil.make_archive (base_name, format,...) Create a zip file and return the file path, such as zip, tar'''
Base_name: the file name of the compressed package, or the path of the compressed package. If it is just a file name, save it to the current directory, otherwise save to the specified path
For example: www = > Save to the current path
For example: / Users/wupeiqi/www = > Save to / Users/wupeiqi/
Format: compressed package type, "zip", "tar", "bztar", "gztar"
Root_dir: the folder path to be compressed (default current directory)
Owner: user, default current user
Group: group, default current group
Logger: used for logging, usually logging.Logger objects
''
# compress the folder of C:\ Users\ admin\ PycharmProjects\ S14\ Day4 into testaa.zipshutil.make_archive ("testaa", "zip", r "C:\ Users\ admin\ PycharmProjects\ S14\ Day4") zipfile compress the file or folder zipfile use import zipfile# to compress the files main.py and test11.py into the compressed file z = zipfile.ZipFile ('day5.zip') of day5.zip 'w') z.write ('main.py') z.write ("test11.txt") z.close () # decompress the newly compressed day5.zip file into the original file z = zipfile.ZipFile (' day5.zip', 'r') z.extractall () z.close () 5. Shelve module
Function: the shelve module is a simple kline v module that persists memory data through files, and can persist any python data format supported by pickle.
Shelve persistence import shelveimport datetime#1 first uses shelve to read the list of dictionaries defined in .py into the specified file shelve_test In fact, we don't have to care about how it is stored in the file d = shelve.open ('shelve_test') # Open a file info = {"age": 22, "job": "it"} name = ["alex", "rain" "test"] d ["name"] = name # persistence list d ["info"] = infod ["date"] = datetime.datetime.now () d.close () # 2 here we can retrieve the content just read from the shelve_test file d = shelve.open ('shelve_test') # open a file print (d.get ("name")) # [' alex' " 'rain',' test'] print (d.get ("info")) # {'job':' it', 'age': 22} print (d.get ("date")) # 2017-11-2017: 54:21.223410json and pickle serialization 1, json serialization
Serialization (json.dumps): stores objects in memory to the hard disk and turns them into strings
Deserialization (json.loads): reloads the memory object that has just been saved on the hard disk into memory
Json.dumps (data,ensure_ascii=False, indent=4)
Json serialization
# json serialization code import jsoninfo = {'name': "tom", "age": "100"} f = open (" test.txt ",' w') # print (json.dumps (info)) f.write (json.dumps (info)) f.close ()
Json deserialization
# json deserialization code import jsonf = open ("test.txt", "r") data = json.loads (f.read ()) f.close () print (data ["age"]) 2, pickle serialization
Python's pickle module implements all data sequences and deserialization of python. Basically, there is not much difference between the functional use and the JSON module, and the methods are also dumps/dump and loads/load.
Unlike JSON, pickle is not used for data transfer between multiple languages, it is only used as a persistence of python objects or a way for python programs to transfer objects to each other, so it supports all data types of python.
Pickle serialization
# pickle serialization code import pickleinfo = {'name': "tom", "age": "100"} f = open (" test.txt ",' wb') f.write (pickle.dumps (info)) f.close ()
Pickle deserialization
# pickle deserialization code import picklef = open ("test.txt", "rb") data = pickle.loads (f.read ()) f.close () print (data ["age"]) 3, solve JSON can't serialize datetime type solve json can't serialize time format import json,datetimeclass JsonCustomEncoder (json.JSONEncoder): def default (self, field): if isinstance (field) Datetime.datetime): return field.strftime ('% Y-%m-%d% HGV% MVR% S') elif isinstance (field, datetime.date): return field.strftime ('% Ymuri% Mmure% d') else: return json.JSONEncoder.default (self, field) t = datetime.datetime.now () print (type (t), t) f = open ('ttt') 'w') # specifies that the content is written to the ttt file f.write (json.dumps (tthencoder JsonCustomEncoder)) # only need to add a cls parameter to json.dumps when using it. 4. The difference between JSON and pickle modules
JSON can only handle basic data types. Pickle can handle all Python data types.
JSON is used for character conversion between various languages. Pickle is used for persistence of Python program objects or network transfer of objects between Python programs, but there may be differences between different versions of Python serialization.
Hashlib module
1. Used for encryption-related operations, replacing md5 module and sha module, mainly providing SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithms
Five simple encryption methods import hashlib # 1 # md5 # purpose: to md5 encrypt the sentence b "HelloIt's me" m = hashlib.md5 () # 1) generate a md5 encryption object m.update (b "Hello") # 2) encrypt m.update (b "It's me") using m to b "Hello" ") # 3) using m to encrypt b" It's me "print (m.hexdigest ()) # 4) the final encryption result is the MD5 value encrypted to b" HelloIt's me ": 5ddeb47b2f925ad0bf249c52e342728a#2 # sha1 # hash = hashlib.sha1 () hash.update (bounded admin') print (hash.hexdigest ()) # 3 # sha256 # # hash = hashlib.sha256 () hash.update (baked admins') print (hash.hexdigest ()) # 4 # sha384 # hash = hashlib.sha384 () hash.update (baked admins') print (hash.hexdigest ()) # 5 # sha512 # hash = hashlib.sha512 () hash.update (bounded admins') print (hash.hexdigest ())
2. Although the above encryption algorithm is still very powerful, it has some defects, that is, it can be solved by hitting the library. Therefore, it is necessary to add custom key to the encryption algorithm to do encryption.
Hmac add Custom key encryption
# hmac # import hmach = hmac.new (b "123456", "real content to be transmitted". Encode (encoding= "utf-8") print (h.digest ()) print (h.hexdigest ()) # Note: hmac is a double encryption method. The front is the encrypted content, followed by the real data information to be transmitted. 6. Subprocess module 1, subprocess principle and commonly used encapsulation functions
When we run python, we are all creating and running a process. Like the Linux process, a process can fork a child process and let that child process exec another program
In Python, we use the subprocess package in the standard library to fork a child process and run an external program.
Several functions for creating child processes are defined in the subprocess package, each of which is created in different ways, so we can choose one of them to use as needed.
In addition, subprocess provides tools for managing standard streams (standard stream) and pipes (pipe) to use text communication between processes.
Common functions of subprocess
# 1. Return the execution status: 0 successfully executed
Retcode = subprocess.call (['ping',' www.baidu.com','- c5'])
# 2. Return the execution status: 0 is executed successfully, otherwise an exception is thrown
Subprocess.check_call (["ls", "- l"])
# 3. The execution result is a tuple: the first element is the execution status, and the second is the command result
> ret = subprocess.getstatusoutput ('pwd') > ret (0,' / test01')
# 4. The returned result is a string.
> ret = subprocess.getoutput ('ls-a') > ret'.\ n..\ ntest.py'
# 5. The returned result is' bytes''.
> res=subprocess.check_output (['ls','-l']) > the total dosage of res.decode (' utf8')'is 4\ n-rwxrwxrwx. 1 root root 334 November 21 09:02 test.py\ n'
Convert dos format files to unix format
Subprocess.check_output (['chmod',' + Xerox, filepath]) subprocess.check_output (['dos2unix', filepath]) 2, subprocess.Popen ()
In fact, the above functions are based on the wrapper of Popen (), which are designed to make it easy for us to use child processes
When we want to more personalize our requirements, we turn to the Popen class, which generates objects that represent child processes.
Unlike the encapsulation above, after the Popen object is created, the main program does not automatically wait for the child process to complete. We must call the object's wait () method before the parent process waits (that is, blocking block).
From the running results, we can see that the parent process does not wait for the completion of child after starting the child process, but runs print directly.
Chil
# 1. Print 'parent process' first without waiting for the completion of child import subprocesschild = subprocess.Popen ([' ping','-c','4','www.baidu.com']) print ('parent process') # 2, then print' parent process' wait for the completion of child import subprocesschild = subprocess.Popen ('ping-c4 www.baidu.com') Shell=True) child.wait () print ('parent process') child.poll () # check the status of the child process child.kill () # terminate the child process child.send_signal () # send a signal to the child process child.terminate () # terminate the child process 3, subprocess.PIPE connects the inputs and outputs of multiple child processes together
Subprocess.PIPE actually provides a cache for text streams. The stdout of child1 outputs the text to the cache, and then the stdin of child2 reads the text from the PIPE
The output text of the child2 is also stored in PIPE until the communicate () method reads the text in the PIPE from the PIPE.
Note: communicate () is a method of the Popen object that blocks the parent process until the child process completes.
Execute cat / etc/passwd step by step | grep root life
The following command executed by import subprocess# is equivalent to: cat / etc/passwd | grep rootchild1 = subprocess.Popen (["cat", "/ etc/passwd"], stdout=subprocess.PIPE) child2 = subprocess.Popen (["grep", "root"], stdin=child1.stdout Stdout=subprocess.PIPE) out= child2.communicate () # returns the execution result as tuple print (out) # execution result: (b'root:x:0:0:root:/root:/bin/bash\ noperator:x:11:0:operator:/root:/sbin/nologin\ n execution, None)
Get the execution result of ping command
Import subprocesslist_tmp = [] def main (): P = subprocess.Popen (['ping',' www.baidu.com','- c5'], stdin = subprocess.PIPE Stdout = subprocess.PIPE) while subprocess.Popen.poll (p) = = None: r = p.stdout.readline (). Strip (). Decode ('utf-8') if r: # print (r) v = p.stdout.read (). Strip (). Decode (' utf-8') list_tmp.append (v) main () print (list_tmp [0]) 7. Regular expression symbols ⒈ wildcards are commonly used in re modules (. )
Function: dot (.) can match any string except newline characters.
For example: '.ython' can match 'aython'' bython', etc., but can only match one string
⒉ escape character (\)
Function: other strings with special meaning can be expressed in the original meaning.
For example: 'python.org'' because there is a special meaning string (.) in the string, so if you want to use it in the general sense, you must use the expression: 'python.org' so it only matches' python.org'.
Note: if you want to escape the backslash (\) itself, you can use double backslash (\), which means'\'.
⒊ character set
Function: use parentheses to enclose the string to create a character set that can match any string it includes
①'[pj] ython' can only match 'python'' jython'
②'[amurz] 'can match any character of amerz (in alphabetical order)
③'[a-zA-Z0-9] 'can match any uppercase and lowercase letter and number
④'[^ abc] 'can match any string except aformaine b and c
⒋ pipe symbol
Function: match multiple strings at once
For example: 'python | perl' can match the strings' python' and 'perl'
⒌ optional and repeating submode (add a question mark after the submode? )
Function: add a question mark after the subpattern, and it becomes optional, and it is legal to appear or not appear in the matching string
For example: r'(aa)? (bb)? ccddee' can only match the following situations
'aabbccddee'
'aaccddee'
'bbccddee'
'ccddee'
The beginning and end of a ⒍ string
① 'wicked 'matches a string activated with w
②'^ http' matches a string that begins with 'http'
③'$com' matches a string that ends in 'com'
7. The most commonly used matching method
\ d matches any decimal number; it is equivalent to class [0-9].
\ D matches any non-numeric character; it is equivalent to class [^ 0-9].
\ s matches any white space character; it is equivalent to the class [fv].
\ s matches any non-white space character; it is equivalent to the class [^ fv].
\ w matches any alphanumeric character; it is equivalent to the class [a-zA-Z0-9 _].
\ W matches any non-alphanumeric character; it is equivalent to the class [^ a-zA-Z0-9 _].
\ w * matches all alphabetic characters
\ w + matches at least one character
Re module more detailed expression symbols
'.' By default, any character except\ n is matched. If flag DOTALL is specified, any character is matched, including line breaks.
'^' matches the beginning of the character. If flags MULTILINE is specified, this can also be matched on (r "^ a", "\ nabc\ neee", flags=re.MULTILINE)
Matches the end of the character, or e.search ("foo", "bfoo\ nsdfsf", flags=re.MULTILINE) .group () is also available.
The character before the matching number is 0 or more times, and the result of re.findall ("ab*", "cabb3abcbbac") is ['abb',' ab', 'a']
'+' matches the previous character one or more times, re.findall ("ab+", "ab+cd+abb+bba") result ['ab',' abb']
'?' Match the previous character 1 or 0 times
'{m}' matches the previous character m times
'{ab', m}' matches the previous character n to m times, re.findall ("ab {1 ab', 3}", "abb abc abbcbbb") results in 'abb',' ab', 'abb']
'|' match | left or | right character, re.search ("abc | ABC", "ABCBabcCD") .group () result 'ABC'
(...)' Group matching, re.search ("(abc) {2} a (123 | 456) c", "abcabca456c") .group () result abcabca456c
The'\ A 'matches only from the beginning of the character. Re.search ("\ Aabc", "alexabc") does not match.
'\ Z' matches the end of the character, same as $
'\ d' matches the number 0-9
'\ D' matches non-numeric
'\ w' match [A-Za-z0-9]
The'\ W 'match is not [A-Za-z0-9]
's' matches white space characters,\ t,\ n,\ r, re.search ("\ s +", "ab\ tc1\ n3"). Group () result'\ t'
\ b matches a word boundary, that is, the position between a word and a space. For example, "er\ b" can match "er" in "never", but not "er" in "verb".
\ B matches non-word boundaries. "er\ B" matches "er" in "verb", but not "er" in "never".
Common functions of re module *
⒈ re.compile (pattern [, flags])
1) compile a regular expression pattern into a regular object so that you can use the match and search methods of the regular object
2) after using re.compile, the regular object will be preserved, so when the regular object needs to be used many times, the efficiency will be greatly improved.
Re.compile usage
Import remobile_re = re.compile (r'^ (13 [0-9] | 15 [012356789] | 17 [012356789] | 18 [0-9] | 14 [57]) [0-9] {8} $') ret = re.match (mobile_re,'18538762511') print (ret) # ⒉ search (pattern, string [, flags]) and match (pattern, string [, flags])
1) match: matches the regular expression only from the beginning of the string. A successful match returns matchobject, otherwise none is returned.
2) search: attempts to match all strings of a string with regular expressions. If none of the strings match successfully, return none, otherwise return matchobject
Comparison between match and search
Import rea = re.match ('www.bai',' www.baidu.com') b = re.match ('bai',' www.baidu.com') print (a.group ()) # www.baiprint (b) # None# will match only one c = re.search ('bai') no matter how many matches 'www.baidubaidu.com') print (c) # print (c.group ()) # bai ⒊ split (pattern, string [, maxsplit=0])
Function: format a string into a list in a specified way of segmentation
Import retext ='aa 1bb###2cc3ddd'print (re.split ('\ Warriors, text)) # ['aa',' 1bbcm, '2cc3dddd'] print (re.split ('\ Warriors, text)) # ['aa',' 1bbbaths, '2cc3dddd'] print (re.split ('\ dudes, text)) # ['aa',' bb###', 'cc' 'ddd'] print (re.split (' #', text)) # ['aa 1bbcm, '2cc3dddd'] print (re.split ('# +, text)) # ['aa 1bbcm, '2cc3dddd'] ⒋ findall (pattern, string)
Function: the regular expression re.findall method can return matching substrings in the form of a list
Import rep = re.compile (r'\ daddy') print (p.findall ('one1two2three3four4')) # [' 1mm, '2mm,' 3mm,'4'] print (re.findall ('oaked pr é cor one two2three3four4')) # ['he',' llo'','o'] print (re.findall ('\ wow, 'he.llo, woodworking')) 'wo',' rld'] ⒌ sub (pat, repl, string [, count=0])
1) replace, replace the part of string that matches pattern with repl, replace count at most, and then return the replaced string
2) if there is no string in string that can match pattern, it will be returned intact
3) repl can be a string or a function
4) if repl is a string, the backslash in it will be processed, for example,\ nwill be converted to a newline character, and the backslash plus number will be replaced with the corresponding group, for example,\ 6 represents the content of the sixth group matched by pattern.
Import retest= "Hi, nice to meet you where are you from?" print (re.sub (r'\ s)) # Hi,-nice-to-meet-you-where-are-you-from?print (re.sub (r'\ s)) # Hi,-nice-to-meet-you-where are you from?print (re.sub) # Hi Nice tweets * meet yawns, where are yawns, fr**m? ⒍ escape (string)
1) re.escape (pattern) can escape all characters in a string that may be interpreted as regular operators.
2) if the string is long and contains a lot of special technical characters, and you don't want to enter a lot of backslashes, or if the string comes from the user (for example, get the input through the raw_input function)
You can use this function when you want to use it as part of a regular expression
Import reprint (re.escape ('www.python.org'))
Matching objects and groups group () in the re module
1) the group method returns the string in the pattern that matches the given group. If no matching group number is given, the default is group 0.
2) m.group () = = m.group (0) = all matching characters
Comparison between group (0) and group (1)
Import rea = "123abc321efg456" print (re.search ("([0-9] *) ([Amurz] *) ([0-9] *)) ([0-9] *) # 123abc321print (re.search (" ([0-9] *)) ([0-9] *)) ([0-9] *). Groups () # ('123,' abc' '321') print (re.search ("([0-9] *) ([Amurz] *)) ([0-9] *) # 123print (re.search (" ([0-9] *)) ([Amurz] *) ([0-9] *), a) .group (2) # abcprint (re.search ("([0-9] *)) ([aMuz] *) ([0-9] *)" A) .group (3) # 321import rem = re.match ('(..). * (..) (..)', '123456789') print (m.group (0)) # 123456789print (m.group (1)) # 12print (m.group (2)) # 67print (m.group (3)) # 89
Return matching index for group () match
Import rem = re.match ('www\. (. *)\. Www.baidu.com') print (m.group (1)) # baiduprint (m.start (1)) # 4print (m.end (1)) # 9print (m.span (1)) # (4,9)
Group () matches ip, and the status is returned as tuple
Import retest = 'dsfdf 22 g2323 GigabitEthernet0/3 10.1.8.1 YES NVRAM up eee'# print (re.match (' (\ w. *\ d)\ s + (\ d {1pje 3}\.\ d {1pr 3}\.\ d {1pr 3})\ s+YES\ s+NVRAM\ s + (\ w +)\ s Test) .groups () ret = re.search (r'(\ w*\ /\ d+). *\ s (\ d {1Magne3}\.\ d {1Magne3}\.\ d {1Magne3}). * (\ s+up\ s +), test) .groups () print (ret) # run result: ('GigabitEthernet0/3',' 10.1.8.1') 'up') # 1. (\ w *\ d +\ /\ d +) matching result is: GigabitEthernet0/3#1.1\ d match: match all alphanumeric # 1.2 /\ d match: match all root digits starting with slashes (for example: / 3) # 2. (\ d {1jue 3}\.\ d {1jue 3}\.\ d {1p 3}\.\ d {1prit 3}) match result is : 10.1.8.1. 3.\ s+up\ s + matching result is: the word up Spaces before and after
Other knowledge points of re module
Re matching ignores case, matching newline
Ignore uppercase and lowercase print (re.search ("[Amurz] +", "abcdA"). Group () # abcdprint (re.search ("[Amurz] +", "abcdA", flags=re.I). Group ()) # abcdA# matches with the newline character: #'. Any character except\ n is matched by default. If flag DOTALL is specified, any character is matched. Include newline print (re.search (r ". +", "\ naaa\ nbbb\ nccc"). Group () # aaaprint (re.search (r ". +", "\ naaa\ nbbb\ nccc", flags=re.S) # print (re.search (r ". +", "\ naaa\ nbbb\ nccc") Flags=re.S). Group () several knowledge points used in the aaa bbb ccc calculator
Init_l= [I for i in re.split ('(-\ dmom.\ d)', expression) if I]
a. Split into lists according to strings similar to negative numbers
B. -\ dnumbers.\ d is to match floating point numbers (for example: 3.14)
C. (if I) is to remove empty elements from the list
d. Segmentation result: ['- 1','- 2','* (','- 60','+ 30 + (')
Re.search ('[+-* / (] $', expression_l [- 1])
a. The last element of the matching expression_l list is +, -, *, /, (these five symbols are negative numbers.
New_l= [I for i in re.split ('([+-* / ()])', exp) if I]
a. Split the string into a list according to +, -, *, /, (,) (if it is not a positive or negative number)
Print (re.split ('([+ -])','- 1'2-3 * (22'3) # split into lists by plus or minus sign
Running result: ['','-', '1percent,' +', '2percent,' -','3 (2percent,'+,'3)]
The above is about the content of this article on "how to use Python time module time () and datetime ()". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.