1. 分片的步長,默認爲值1,表示爲 xx[s:t:v] ----從索引s到索引t,每隔v,取對應索引位置的值python
xx = 'hello,world' #從索引0-10,共11個字符 xx[2:] #從索引2直到最後全部的值 Out[2]: 'llo,world' xx[1:5:2] #從索引1到5,即xx[1:5]='ello',注意此時不含xx[5]的值,從xx[1]開始,每隔2取一個值,即取xx[1],xx[3] Out[3]: 'el' xx[::2] #對整個序列,此時序列包含末尾值,從xx[0]開始,每隔2取一個值,即取xx[0],xx[0+2],xx[2+2],xx[4+2],xx[6+2],xx[8+2] Out[4]: 'hlowrd' ##注意:python索引是從0開始
2. 步長爲負數時,有時候頗有用,例如用於序列反轉函數
##注意:python在負數索引時,序列的最後一位索引爲-1,所以從右往左,依次是-1,-2,-3, ... xx[::-1] #能夠理解爲先取整個序列,而後從索引0開始,依次取xx[0-1]也就是xx[-1],xx[-1-1]也就是xx[-2],xx[-3],...的值,也就是反轉序列 Out[6]: 'dlrow,olleh' xx[7:2:-1] #從索引7開始,每次-1,反轉子序列,即xx[7],xx[6],...,可是一樣不包含xx[2]的值 Out[7]: 'ow,ol'
3. 字符串轉數字,數字轉字符串spa
int('30') #'30'自己是一個字符串 Out[9]: 30 float('30') Out[10]: 30.0 str(30) Out[11]: '30'
4. 字符與ASCII碼轉化code
ord('a') #ord函數獲取字符的ASCII碼值 Out[12]: 97 chr(97) #chr函數獲取ASCII對應的字符 Out[13]: 'a'
5. 複數表示blog
2+-4j #通常用下面一種方法比較容易看,均可以獲得複數2-4j Out[14]: (2-4j) 2-4j Out[15]: (2-4j)
6. 按位與、按位或索引
1 & 2 #二進制:0001 & 0010 = 0000 Out[18]: 0 1 & 1 # 0001 & 0001 = 0001 Out[19]: 1 1 | 2 # 0001 | 0010 = 0011 Out[21]: 3
7. 除法(/)與floor除法(//)字符串
5/3 #直接除法 Out[16]: 1.6666666666666667 5//3 #floor除法結果,取小於1.66666666666666667的最大整數,也就是1 Out[17]: 1 5//-3 #取小於-1.66666666666666667的最大整數,也就是-2 Out[22]: -2
## 注:'%'對應數字時是取餘數操做
8. math.floor和math.ceil函數class
import math math.floor(5/3) #同floor除法的解釋 Out[25]: 1 math.floor(5/-3) Out[28]: -2 math.ceil(5/3) #取大於1.666666666667的最小整數 Out[26]: 2 math.ceil(5/-3) #取大於-1.6666666666667的最小整數 Out[27]: -1