python函數和常用模組(三),Day5,pythonday5

來源:互聯網
上載者:User

python函數和常用模組(三),Day5,pythonday5

  • 遞迴
  • 反射
  • os模組
  • sys模組
  • hashlib加密模組
  • Regex

 

 反射

python中的反射功能是由以下四個內建函數提供:hasattr、getattr、setattr、delattr,改四個函數分別用於對對象內部執行:檢查是否含有某成員、擷取成員、設定成員、刪除成員。

class Foo(object):     def __init__(self):        self.name = 'wupeiqi'     def func(self):        return 'func' obj = Foo() # #### 檢查是否含有成員 ####hasattr(obj, 'name')hasattr(obj, 'func') # #### 擷取成員 ####getattr(obj, 'name')getattr(obj, 'func') # #### 設定成員 ####setattr(obj, 'age', 18)setattr(obj, 'show', lambda num: num + 1) # #### 刪除成員 ####delattr(obj, 'name')delattr(obj, 'func')
os模組
os.getcwd()                 # 擷取當前工作目錄,即當前python指令碼工作的目錄路徑os.chdir("dirname")         # 改變當前指令碼工作目錄;相當於shell下cdos.curdir                   # 返回目前的目錄: ('.')os.pardir                   # 擷取目前的目錄的父目錄字元串名:('..')os.makedirs('dir1/dir2')    # 可產生多層遞迴目錄os.removedirs('dirname1')   # 若目錄為空白,則刪除,並遞迴到上一級目錄,如若也為空白,則刪除,依此類推os.mkdir('dirname')         # 產生單級目錄;相當於shell中mkdir dirnameos.rmdir('dirname')         # 刪除單級空目錄,若目錄不為空白則無法刪除,報錯;相當於shell中rmdir dirnameos.listdir('dirname')       # 列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印os.remove()                 # 刪除一個檔案os.rename("oldname","new")  # 重新命名檔案/目錄os.stat('path/filename')    # 擷取檔案/目錄資訊os.sep                      # 作業系統特定的路徑分隔字元,win下為"\\",Linux下為"/"os.linesep                  # 當前平台使用的行終止符,win下為"\t\n",Linux下為"\n"os.pathsep                  # 用於分割檔案路徑的字串os.name                     # 字串指示當前使用平台。win->'nt'; Linux->'posix'os.system("bash command")   # 運行shell命令,直接顯示os.environ                  # 擷取系統內容變數os.path.abspath(path)       # 返回path正常化的絕對路徑os.path.split(path)         # 將path分割成目錄和檔案名稱二元組返回os.path.dirname(path)       # 返回path的目錄。其實就是os.path.split(path)的第一個元素os.path.basename(path)      # 返回path最後的檔案名稱。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素os.path.exists(path)        # 如果path存在,返回True;如果path不存在,返回Falseos.path.isabs(path)         # 如果path是絕對路徑,返回Trueos.path.isfile(path)        # 如果path是一個存在的檔案,返回True。否則返回Falseos.path.isdir(path)         # 如果path是一個存在的目錄,則返回True。否則返回Falseos.path.join(path1[, path2[, ...]])  # 將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略os.path.getatime(path)      # 返回path所指向的檔案或者目錄的最後存取時間os.path.getmtime(path)      # 返回path所指向的檔案或者目錄的最後修改時間
sys模組
sys.argv  # 命令列參數List,第一個元素是程式本身路徑sys.exit(n)  # 退出程式,正常退出時exit(0)sys.version  # 擷取Python程式的版本資訊sys.maxint  # 最大的Int值sys.path  # 返回模組的搜尋路徑,初始化時使用PYTHONPATH環境變數的值sys.platform  # 返回作業系統平台的名稱sys.stdin  # 輸入相關sys.stdout  # 輸出相關sys.stderror  # 錯誤相關
hashlib加密模組

用於加密相關的操作,代替了md5模組和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法

import hashlib # ######## md5 ######## hash = hashlib.md5()hash.update('admin')print hash.hexdigest() # ######## sha1 ######## hash = hashlib.sha1()hash.update('admin')print hash.hexdigest() # ######## sha256 ######## hash = hashlib.sha256()hash.update('admin')print hash.hexdigest()  # ######## sha384 ######## hash = hashlib.sha384()hash.update('admin')print hash.hexdigest() # ######## sha512 ######## hash = hashlib.sha512()hash.update('admin')print hash.hexdigest()

以上密碼編譯演算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對密碼編譯演算法中添加自訂key再來做加密。

import hashlib # ######## md5 ######## hash = hashlib.md5('898oaFs09f')hash.update('admin')print hash.hexdigest()

還不夠吊?python 還有一個 hmac 模組,它內部對我們建立 key 和 內容 再進行處理然後再加密

import hmach = hmac.new('wueiqi')h.update('hellowo')print h.hexdigest()

不能再牛逼了!!!

import hashlibobj = hashlib.md5()obj.update(bytes('admin', encoding='utf-8'))result = obj.hexdigest()print(result)# 加key密鑰obj = hashlib.md5(bytes('xxxxxxxx', encoding='utf-8'))obj.update(bytes('admin', encoding='utf-8'))result = obj.hexdigest()print(result)

Regex

re模組用於對python的Regex的操作。

字元:

  . 匹配除分行符號以外的任一字元
  \w匹配字母或數字或底線或漢字
  \s匹配任意的空白符
  \d匹配數字
  \b匹配單詞的開始或結束
  ^匹配字串的開始
  $匹配字串的結束

次數:

  * 重複零次或更多次
  +重複一次或更多次
  ?重複零次或一次
  {n}重複n次
  {n,}重複n次或更多次
  {n,m}重複n到m次

IP:^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$手機號:^1[3|4|5|8][0-9]\d{8}$

1、match(pattern, string, flags=0)

從起始位置開始根據模型去字串中匹配指定內容,匹配單個

  • Regex
  • 要匹配的字串
  • 標誌位,用於控制Regex的匹配方式
import reobj = re.match('\d+', '123uuasf')if obj:    print obj.group()

2、search(pattern, string, flags=0)

根據模型去字串中匹配指定內容,匹配單個

import reobj = re.search('\d+', 'u123uu888asf')if obj:    print obj.group()

3、group和groups

a = "123abc456"print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group()print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()

4、findall(pattern, string, flags=0)

上述兩中方式均用於匹配單值,即:只能匹配字串中的一個,如果想要匹配到字串中所有合格元素,則需要使用 findall。

import reobj = re.findall('\d+', 'fa123uu888asf')print obj

5、sub(pattern, repl, string, count=0, flags=0)

用於替換匹配的字串

content = "123abc456"new_content = re.sub('\d+', 'sb', content)# new_content = re.sub('\d+', 'sb', content, 1)print new_content

相比於str.replace功能更加強大

6、split(pattern, string, maxsplit=0, flags=0)

根據指定匹配進行分組

content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('\*', content)# new_content = re.split('\*', content, 1)print new_content
content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('[\+\-\*\/]+', content)# new_content = re.split('\*', content, 1)print new_content
inpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))'inpp = re.sub('\s*','',inpp)new_content = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)', inpp, 1)print new_content

相比於str.split更加強大  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.