python 序列:字串、列表、元組,python字串
python 序列:字串、列表、元組 序列:包含一定順序排列的對象的一個結構內建函數:str() list() tuple()可以使用str(obj)可以把對象obj轉換成字串list(iterj)可以把可迭代對象inter轉換成列表tuple(inter)可以把可迭代對象inter轉換成一個元組·2 序列切片操作符:“[ ]” 、 “[:]” 、“[::]” 例:>>>x = 'abcde'函數len() 可以計算x 的長度值:len(x) = 50 1 2 3 4為正向索引-5 -4 -3 -2 -1 反向索引正索引是開始於0,結束於總長度減1負索引是從-1開始從尾部反向計數,結束於總長度的負值0 1 2 3 4' a b c d e '-5 -4 -3 -2 -1>>>x[0]'a'>>>x[4]'e'>>>x[-1]'e'>>>x[-5]'a'>>>len(x)5>>>x[1] == x[-4]True 幾個函數使用:>>>x = list(range(10))>>>x[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>x = tuple(range(10))>>>x(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)成員操作符: in 、not in>>>x = 'abcd'>>>'c' in xTrue>>>'a' not in xFalse此操作符也適合列表和元組 學到的幾個內建函數:enumerate()說明enumerate在字典上是枚舉、列舉的意思對於一個可迭代的(iterable)/可遍曆的對象(如列表、字串),enumerate將其組成一個索引序列,利用它可以同時獲得索引和值 多用於for迴圈得到計數如:>>>x = 'abcd'>>>for i,t in enumerate(x):. . . print(i,t). . .0 a1 b2 c3 d可以得到如上結果字串操作其他函數>>>x = 'abcd'>>>x.capitalize() #使得x首寫字母大寫'Abcd'>>>x.count('m',begin,len(x)) #尋找x中字元‘m'的出現次數>>>x.find('m',begin,len(x)) #查看字元’m‘是否在x中,若存在則返回字元所在序號,沒有返回-1>>>x.endswith('m',begin,len(x)) #查看x是否以字元m結尾,若添加範圍begin到len(x)則在查看選中範圍判斷x.split(str='') #以str為分隔字元切片x x.lstrip() #去掉左邊的空格x.rstrip() #去掉右邊的空格x.strip() #同時使用lstrip和rstrip