Python基本類型
Python是一門動態語言,解釋執行,所有錯誤都是運行時產生的,即使有錯誤和異常,只要沒有被執行到也不會有錯,比如調用不存在的方法;類型是隱式的,也即無需變量類型聲明;類型是動態,運行時根據變量指向的內容來決定類型,但是Python是強類型語言,即每個變量都是有類型的。
Python 基本built-in類型主要有numerics,sequences, mapping, files, classes, instances, exceptions,類型上都會存在的操作有比較、是否為真、轉換為字符串toString,Python中使用str/repr(object)可轉換為字符串, print(object)時會隱式調用str()。 numerics:
整形 int,用c語言中的long實現, 取值范圍-sys.maxint-1~sys.maxin, 無sys.minint
長整形 long, 帶有L/l的integer或超出integer范圍的,print時會帶后綴L,無精度限制,無限大,因此Python中都是有符號數,沒有unsigned類型
浮點型 float,用c中的double實現,sys.float_info, 因此Python中無單雙精度區分
復數 complex, z.real, z.imag
Operation | Result | Notes |
---|---|---|
x + y | sum of x and y | |
x - y | difference of x and y | |
x * y | product of x and y | |
x / y | quotient of x and y | (1) |
x // y | (floored) quotient of x and y | (4)(5) |
x % y | remainder of x / y | (4) |
-x | x negated | |
+x | x unchanged | |
abs(x) | absolute value or magnitude of x | (3) |
int(x) | x converted to integer | (2) |
long(x) | x converted to long integer | (2) |
float(x) | x converted to floating point | (6) |
complex(re,im) | a complex number with real part re, imaginary part im. im defaults to zero. | |
c.conjugate() | conjugate of the complex number c. (Identity on real numbers) | |
divmod(x, y) | the pair (x // y, x % y) | (3)(4) |
pow(x, y) | x to the power y | (3)(7) |
x ** y | x to the power y | (7) |
不同類型的numerics可以混合運算,遵循規則類似c,也即小范圍向大范圍轉型,int<long<float<complex
整除/ : 結果總是整數,哪怕除數、被除數不是整數,而且結果總是趨向負無窮大,-1/2=-1
0的0次冪:pow(0,0) =1, 0**0=1
NaN: not a number , INF:無窮大,-inf +inf , float('nan') float('+inf') float('-inf')
int(), long() 都是向下轉型,對應實數int long float還可以用以下方式取舍:
Operation | Result | Notes |
---|---|---|
math.trunc(x) | x truncated to Integral | |
round(x[, n]) | x rounded to n digits, rounding ties away from zero. If n is omitted, it defaults to 0. | 四舍五入 |
math.floor(x) | the greatest integral float <= x | |
math.ceil(x) | the least integral float >= x |
bool布爾:用于if/while后做條件判斷
True:非False即為True
False: None, False, 數字類型0,空容器,包括空字符串‘’, class的__nonzero__() 或__len__返回0或False的實例
bool運算符:or and not, 遵循類似java/c的short-circuit, not比non-Boolean operator優先級低,not a==b 等價于not (a==b)
比較運算符: 也用于所有類型的比較,優先級比Boolean operator高,且支持x<y<z這樣的寫法,x<y<z 等價x<y and y < z 且前者y僅計算一次,都遵循短路原則;不同類型的對象比較結果都是False,除非是不同類型數字或字符串比較,比如0==0L, ‘abc’==u'abc'返回True
Operation | Meaning | Notes |
---|---|---|
< | strictly less than | |
<= | less than or equal | |
> | strictly greater than | |
>= | greater than or equal | |
== | equal | |
!= 或 <> | not equal | (1) |
is | object identity | |
is not | negated object identity |
bitwise operation: 位運算只對整數操作有意義,位運算優先級比數字運算符低,但比比較運算符高; ~與其他的一元運算符優先級(+,-)相同,以下表格中優先級從低到高, 負數移位會拋出ValueError異常
Operation | Result | Notes |
---|---|---|
x | y | bitwise or of x and y | |
x ^ y | bitwise exclusive or of x andy | |
x & y | bitwise and of x and y | |
x << n | x shifted left by n bits | (1)(2) |
x >> n | x shifted right by n bits | (1)(3) |
~x | the bits of x inverted |
int.bit_length():獲取int bit表示長度
long.bit_length():獲取long bit表示長度
字符:長度為1的字符串,也即沒有單個字符
字符串: 單引號'abc' 或雙引號''abc" 或三個連續單/雙引號'''表示多行字符串,字符串可理解為常量字節數組或字節容器,類似Java中String,也不能通過變量改變指向的字符串, s='abc'; id(s) == id('abc')。
字符串上常用操作:
長度:容器統一用len(),
子串:容器分片操作符[] 'abcd'[1:3]='bc'
分隔:split/rsplit
查找/替換:find/rfind 沒找到返回-1; index/rindex沒找到拋ValueError, replace
trim: strip/lstrip/rstrip
編/解碼:只能對str解碼 str('漢').decode('UTF-8'), 只能對Unicode編碼 u('漢').encode('UTF-8')
大小寫轉換: lower/uper
判斷:isalnum/isalpha/isdigit/islower/isspace/isupper/startwith/endwith
格式化: %+tuple/dict,類似c語言sprintf,一個參數'%d' % 1 = '1' ; 兩個參數'%s, %s' %('a','b') = 'a,b'; 指
定占位符%(mapping key)+類型字符,mapping key需加括號'%(key1)s, %(key2)d' %{'key1':'a', 'key2':1}='a,1'
Python中很容易獲取幫助:
help(object):顯示幫助信息
dir(object) :顯示所有方法
object.__doc__ :顯示文檔
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!