搜尋
首頁後端開發Python教學使用Python常用函數說明

使用Python常用函數說明

Mar 17, 2017 pm 04:26 PM
python

基本客製化型

C.init(self[, arg1, ...]) 建構器(帶一些可選的參數)

C.new(self[, arg1, ...]) 建構器(帶一些可選的參數);通常用在設定不變資料型別的子類別。

C.del(self) 解構器

C.str(self) 可列印的字元輸出;內建str()及print 語句

C.repr(self) 執行時期的字串輸出;內建repr() 和'' 運算元

##C.unicode(self)b Unicode 字串輸出;內建unicode()

C.c

all(self, *args) 表示可呼叫的實例

C.nonzero(self) 為

object 定義False 值;內建bool() (從2.2 版開始)

C.len(self) 「長度」(可用來類別);內建len()

特殊方法   描述

物件(值)比較c

C.cmp(self, obj)

物件比較;內建cmp()

C.lt(self, obj) and 小於/小於或等於;對應C.gt(self, obj) and 大於/大於或等於;對應>且>=運算子

C.eq(self, obj) and 等於/不等於;對應==,!=且運算子

#屬性

C.getattr(self, attr) 取得屬性;內建getattr();僅當屬性找不到時呼叫

C.

setattr(self, attr, val) 設定屬性

C.delattr(self, attr)

刪除屬性##C.getattribute(self, attr) 取得屬性;內建getattr();總是被呼叫

C.get(self, attr) (描述子)取得屬性

C.set(self, attr, val)  (描述子)設定屬性

C.

delete

(self, attr)  (描述子)刪除屬性自訂類別/類比類型

##數值類型

:二進位運算子

C.*add(self, obj) 加;+運算子

C.*sub(self, obj) 減;-運算子

C.*mul(self, obj) 乘;*運算子

C.*p(self, obj) 除;/運算子

C.*truep(self, obj)  True 除;/運算符

C.*floorp(self, obj)  Floor 除;//運算符

C.*mod(self, obj) 取模/取餘;%運算子

C.*pmod(self, obj) 除與取模;內建pmod()

C.*pow(self, obj[, mod]) 乘冪;內建pow();**運算子

C.*lshift(self, obj) 左移位; 特殊方法描述

#自訂類別/模擬類型

數值類型:二進位運算子

C.*rshift(self, obj) 右移;>>運算子

#C. *and(self, obj) 位元與;&運算子

C.*or(self, obj) 位元或;|運算子

C.*xor(self, obj ) 按位元與或;^運算子

數值型別:一元運算子

C.neg(self) 一元負

C.pos(self) 一元正

C.abs(self) 絕對值;內建abs()

C.invert(self) 以位元求反;~運算子

數值類型:數值轉換

C.complex(self, com) 轉為complex(複數);內建complex()

C.int(self) 轉為int;內建int()

C.long(self) 轉為long;內建long()

C.

float

(self) 轉為float;內建float()

數值類型:基本表示法(String

C.oct(self) 八進位表示;內建oct()

C.hex(self) 十六進位表示;內建hex()

數值型別:數值壓縮

C.coerce(self, num) 壓縮成同樣的數值型別;內建coerce()

C.index(self)g 在有必要時,壓縮可選的數值類型為整數(例如:用於切片

#索引等等

序列類型

#C.len(self) 序列中項的數目

C.getitem(self, ind) 得到單一序列元素

C.setitem(self, ind,val) 設定單一序列元素

C.delitem(self, ind) 刪除單一序列元素

特殊方法描述

序列類型

C.getslice(self, ind1, ind2) 得到序列片段

C.setslice(self, i1, i2,val) 設定序列片段

C.delslice(self, ind1,ind2) 刪除序列片段

#C.contains(self, val) f 測試序列成員;內建in 關鍵字

C.*add(self,obj) 串連;+運算子

C.*mul (self,obj) 重複;*運算子

C.iter(self)  建立迭代類別;內建iter()

映射類型

C.len(self ) mapping 中的項的數目

C.hash(self) 雜湊(hash)函數

C.getitem(self,key) 得到給定鍵(key)的值

C.setitem(self,key,val) 設定給定鍵(key)的值

C.delitem(self,key) 刪除給定鍵(key)的值

C.missing(self,key) 給定鍵如果不存在字典中,則提供一個預設值

記幾個常用的python函數,免得忘

取得檔案副檔名函數:傳回副檔名和擴充名之前的檔案名稱路徑。

os.path.splitext('xinjingbao1s.jpg')

('xinjingbao1s', '.jpg')

os和os.path模組

#os.listdir(dirname):列出dirname下的目錄和檔案

os.getcwd():取得目前工作目錄

os.curdir:傳回但前目錄('. ')

os.chdir(dirname):改變工作目錄到dirname

os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就回傳false

os.path.isfile(name):判斷name是不是一個文件,不存在name也回傳false

os.path.exists(name):判斷是否存在文件或目錄name

os.path.getsize(name):取得檔案大小,如果name是目錄回傳0L

os.path.abspath(name):取得絕對路徑

os.path .normpath(path):規範path字串形式

os.path.split(name):分割檔案名稱與目錄(事實上,如果你完全使用目錄,它也會將最後一個目錄作為文件名而分離,同時它不會判斷檔案或目錄是否存在)

os.path.splitext():分離檔案名稱與副檔名

os.path.join(path,name ):連線目錄與檔名或目錄

os.path.basename(path):回傳檔名

os.path.dirname(path):傳回檔案路徑

1.重新命名:os.rename(old, new)

2.刪除:os.remove(file)

3.列出目錄下的檔案:os.listdir(path )

4.取得目前工作目錄:os.getcwd()

5.改變工作目錄:os.chdir(newdir)

6.建立多層目錄: os.makedirs(r"c:\python\test")

7.建立單一目錄:os.mkdir("test")

8.刪除多個目錄:os.removedirs (r"c:\python") #刪除所給路徑最後一個目錄下所有空目錄。

9.刪除單一目錄:os.rmdir("test")

10.取得檔案屬性:os.stat(file)

11.修改檔案權限與時間戳記:os.chmod(file)

12.執行作業系統指令:os.system("dir")

13.啟動新進程:os.exec(), os. execvp()

14.在背景執行程式:osspawnv()

15.終止目前處理:os.exit(), os._exit()

16.分離檔名:os.path.split(r"c:\python\hello.py") --> ("c:\\python", "hello.py")

17.分離副檔名:os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello", ".py")

#18.取得路徑名稱:os.path.dirname(r"c:\python\hello.py") --> "c:\\python"

19.取得檔案名稱:os.path.basename (r"r:\python\hello.py") --> "hello.py"

#20.判斷檔案是否存在:os.path.exists(r"c:\python\hello. py") --> 真

21.判斷是否為絕對路徑:os.path.isabs(r".\python\") --> False

22.判斷是否為目錄:os.path.isdir(r"c:\python") --> True

23.判斷是否為檔案:os.path.isfile(r"c:\python\hello .py") --> True

24.判斷是否為連結檔:os.path.islink(r"c:\python\hello.py") --> False

#25.取得檔案大小:os.path.getsize(filename)

26.*******:os.ismount("c:\\") --> True

27.搜尋目錄下的所有檔案:os.path.walk()

[2.shutil]

#1.複製單一檔案:shultil.copy(oldfile, newfle)

2.複製整個目錄樹:shultil.copytree(r".\setup", r".\backup")

3.刪除整個目錄樹:shultil.rmtree(r".\backup")

[3.tempfile]

1.建立一個唯一的暫存檔案:tempfile.mktemp() --> filename

2.開啟臨時檔案:tempfile.TemporaryFile()

[4.StringIO] #cStringIO是StringIO模組的快速實作模組

1.建立記憶體檔案並寫入初始資料:f = StringIO.StringIO("Hello world!")

2.讀入記憶體檔案資料:print f.read() #或print f.getvalue() --> Hello world!

3.想記憶體檔案寫入資料:f.write("Good day!")

#4.關閉記憶體檔案:f.close()

檢視原始程式碼列印幫助1 from time import * 

2    

#3 def secs2str(secs):  

4         return strftime("%Y-%m-%d %H:%M:%S",localtime(secs))  5

5

6 >>> secs2str(1227628280.0)  

7 '2008-11-25 23:51:20' 

將指定的struct_time(預設為目前時間),根據指定的格式化字串輸出

python中時間日期格式化符號:

%y 兩位數的年份表示(00-99)

%Y 四位數的年份表示(000-9999)

%m 月份(01-12)

%d 月內中的一天(0-31)

%H 24小時制小時數(0-23)

%I 12小時制小時數(01-12)

# %M 分鐘數(00=59)

%S 秒(00-59)

%a 本地簡化星期名稱

%A 本地完整星期名稱

%b 本地簡化的月份名稱

%B 本地完整的月份名稱

%c 本地相應的日期表示和時間表示

%j 年內的一天(001-366)

%p 本地A.M.或P.M.的等價符

%U 一年中的星期數(00-53)星期日為星期的開始

%w 星期(0-6),星期日為星期的開始

%W 一年中的星期數(00-53)星期一為星期的開始

%x 本地相應的日期表示

%X 本地對應的時間表示

#%Z 目前時區的名稱

%% %號本身

9. strptime(…)

strptime(string, format) -> struct_time

將時間字串根據指定的格式化符轉換成陣列形式的時間

例如:

2009-03-20 11:45:39 對應的格式化字串為:%Y-%m-%d %H:%M:%S

Sat Mar 28 22:24:24 2009 對應的格式化字串為:%a %b %d %H:%M:%S %Y

#10.time(…)

time() -> floating point number

傳回目前時間的時間戳記

三、疑點

1.夏令時間

#在struct_time中,夏令時好像沒用,例如

a = (2009, 6, 28, 23, 8, 34, 5, 87, 1)

b = (2009 , 6, 28, 23, 8, 34, 5, 87, 0)

a和b分別表示的是夏令時和標準時間,它們之間轉換為時間戳應該相關3600,但是轉換後輸出皆為646585714.0

四、小應用程式

#1.python取得目前時間

time.time() 取得目前時間戳

#time.localtime () 當前時間的struct_time形式

time.ctime() 當前時間的字串形式

2.python格式化字串

##格式化成2009-03-20 11:45:39形式

  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())格式化成Sat Mar 28 22:24: 24 2009形式

  time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())3.將格式字串轉換為時間戳

  a = "Sat Mar 28 22:24:24 2009"

  b = time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

python time datetime模組詳解

Time模組:

---------------------------」 -------

time() #以浮點形式傳回Linux新世紀以來經過的秒數。在linux中,00:00:00 UTC, 

January 1, 1970是新**49**的開始。

>>> time.time()

1150269086.6630149

>>> time.ctime(1150269086.6630149)

##> >> 'Wed Jun 14 15:11:26 2006'

time.ctime([sec])#把秒數轉換成日期格式,如果不帶參數,則顯示目前的時間。

>>> import time

>>> time.ctime()

>>> 'Wed Jun 14 15:02 :50 2006'

>>> time.ctime(1138068452427683)

'Sat Dec 14 04:51:44 1901'

> ; time.ctime(os.path.getmtime('E:\\untitleds.bmp'))

'Fri Sep 19 16:35:37 2008'

>>> ; time.gmtime(os.path.getmtime('E:\\untitleds.bmp'))

time.struct_time(tm_year=2008, tm_mon=9, tm_mday=19, tm_hour=8, tm_min= 35, 

tm_sec=37, tm_wday=4, tm_yday=263, tm_isdst=0)

將一個檔案的修改時間轉換為日期格式(秒轉日期)

>>> time.strftime('%Y-%m-%d %X',time.localtime(os.path.getmtime('E:\\untitleds.bmp')))

'2008-09-19 16:35:37'

#定時3秒。

>>> time.sleep(3) 

TIME模組參考:

#———————————————— -----------------

#取一個檔案的修改時間

>>> os.path.getmtime('E :\\untitleds.bmp')

1221813337.7626641

變數

timezone 通用協調時間和本地標準時間的差值,以秒為單位。

altzone 通用協調時間和本地夏令時的差異

daylight 標誌,本地時間是否反映夏令時。

tzname (標準時區名,夏令時時區名)

函數

#time() 以浮點數傳回紀元至今以來的秒數。

clock() 以浮點數回傳CPU開始這個process的時間,(或至上次呼叫這個函數的時間)

sleep() 延遲一段以浮點數表示的秒數。

gmtime() 把以秒錶示的時間轉換為通用協調時序列

localtime() 把秒轉換為本地時序列

asctime() 將時間序列轉換成文字描述

ctime() 將秒時轉換成文字描述

mktime() 將本地時序列轉換成秒時

strftime() 以指定格式將序列時轉為文字描述

strptime() 以指定格式從文字描述解析出時間序列

tzset() 改變當地時區值

DateTime模組

————————————————————————————

datetime 將日期轉換為秒

- --------------------------------------

>>> import datetime ,time

>>> time.mktime(datetime.datetime(2009,1,1).timetuple())

1230739200.0

>> > cc=[2000,11,3,12,43,33] #Attributes: year, month, day, hour, minute, 

#second

#>>> time .mktime(datetime.datetime(cc[0],cc[1],cc[2],cc[3],cc[4],cc[5]).timetuple())

#973226613.0

將秒數轉換為日期格式

>>> cc = time.localtime(os.path.getmtime('E:\\untitleds.bmp'))

>>> print cc[0:3]

(2008, 9, 19)

DateTime範例

##———————— ---------

示範計算兩個日期相差天數的計算

>>> import datetime

>>> d1 = datetime.datetime(2005, 2, 16)

>>> d2 = datetime.datetime(2004, 12, 31)

#>>> (d1 - d2).days

47

示範計算運行時間的例子,以秒數顯示

import datetime

starttime = datetime.datetime.now ()

#long running

endtime = datetime.datetime.now()

print (endtime - starttime).seconds

#示範計算目前時間向後10小時的時間。

>>> d1 = datetime.datetime.now()

>>> d3 = d1 + datetime.timedelta(hours=10)

>>> d3.ctime()

其本上常用的類別有:datetime和timedelta兩個。它們之間可以相互加減。每個類別都有一些方法和屬性可以查看具體的值


#

以上是使用Python常用函數說明的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。