python中的序列包括字符串、元祖、列表,序列的基本操作包括。元祖和字符串的最大特点是不可变。
- len() 计算序列长度
- + 连接两个序列
- * 重复序列元素
- in 判断元素是否在序列中
- max() 返回最大值
- min() 返回最小值
- cmp(x,y) 比较两个序列是否相等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| In [46]: a Out[46]: 'abcdef'
In [47]: len(a) Out[47]: 6
In [48]: a + 'z' Out[48]: 'abcdefz'
In [49]: a * 3 Out[49]: 'abcdefabcdefabcdef'
In [50]: 'a' in a Out[50]: True
In [51]: 'm' in a Out[51]: False
In [52]: 'm' not in a Out[52]: True
In [53]: max(a) Out[53]: 'f'
In [54]: min(a) Out[54]: 'a'
In [56]: cmp(a,'abcdef') Out[56]: 0
In [57]: cmp(a,'abcdefg') Out[57]: -1
In [58]: cmp(a,'abcde') Out[58]: 1
In [4]: a Out[4]: 'abcde'
In [5]: a[0] Out[5]: 'a'
In [6]: a[0] = 'd' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-3f16016bea5e> in <module>() ----> 1 a[0] = 'd'
TypeError: 'str' object does not support item assignment
|
pthon中的字符串索引是从0开始的, a[0]为a,a[5]为f
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| In [27]: a = 'abcdef'
In [28]: a Out[28]: 'abcdef'
In [29]: a[1] Out[29]: 'b'
In [30]: a[0] Out[30]: 'a'
In [31]: a[1:] Out[31]: 'bcdef'
In [32]: a[:] Out[32]: 'abcdef'
In [33]: a[:-1] Out[33]: 'abcde'
In [34]: a[::] Out[34]: 'abcdef'
In [35]: a[::2] Out[35]: 'ace'
In [36]: a[::1] Out[36]: 'abcdef'
In [37]: a[-1] Out[37]: 'f'
In [38]: a[-4:-1] Out[38]: 'cde'
In [45]: a[4:1:-1] Out[45]: 'edc'
|