2.2.2分片
1.索引用于访问单个元素,可以使用分片操作来访问一定范围内的元素。
>>> tag = '<a herf="http://www.python.org"> Python web site</a>' >>> tag[9:30] 'http://www.python.org' >>> tag[32:-4] ' Python web site'
>>> numbers = [1,2,3,4,5,6,7,8,9,10] >>> numbers[4:6] [5, 6] >>> numbers[0:1] [1]
>>> numbers[7:10]#访问后三个元素 [8, 9, 10] >>> numbers[-3:-1] [8, 9] >>> numbers[-3:] [8, 9, 10] >>> numbers[-3:0]#会发生错误 [] >>> numbers[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>
2_2.py 分片示例
#对http://www.something.com形式的URL进行分割 url = raw_input('Please enter the URL: ') domain = url[11:-4] print "Domain name: " + domain
运行效果:
>>> Please enter the URL: http://www.python.org Domain name: python
2.更大的步长
运行示例:
>>> numbers = [1,2,3,4,5,6,7,8,9,10] >>> numbers[0:10:1] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[0:10:2]#前两个构成范围,最后一个是步长 [1, 3, 5, 7, 9] >>> numbers[3:6:3] [4] >>> numbers[::4] [1, 5, 9] >>> numbers[8:3:-1]#步长可以为负数,但不能为0,表示从右往左提取元素 [9, 8, 7, 6, 5] >>>
2.2.3序列相加
>>> [1,2,3] + [4,5,6] [1, 2, 3, 4, 5, 6] >>> 'Hello,' + 'world!' 'Hello,world!'
2.2.4乘法
运行示例:
>>> 'python' * 5 'pythonpythonpythonpythonpython' >>> [42] * 10 [42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
None是一个Python的内建值,它的确切含意是“这里什么也没有”。如下例子可以初始化一个长度为10的空列表
>>> sequence = [None] * 10 >>> sequence [None, None, None, None, None, None, None, None, None, None]
2_3 序列(字符串)乘法示例
#以正确的宽度在居中的“盒子”内打印一个句子 #注意,整数除法运算符(//)只能用在Python 2.2以及后续版本,在之前的版本中,只是用普通除法(/) # -*- coding: cp936 -*- sentence = raw_input("Sentence: ") screen_width = 80 text_width = len(sentence) box_width = text_width + 6 left_margin = (screen_width - box_width) // 2 print print ' ' * left_margin + '+' + '-' * (box_width - 2) + '+' print ' ' * left_margin + '|' + ' ' * text_width + '|' print ' ' * left_margin + '|' + sentence + '|' print ' ' * left_margin + '|' + ' ' * text_width + '|' print ' ' * left_margin + '+' + '-' * (box_width - 2) + '+' print
运行效果
>>> Sentence: He's a very naughty boy! +----------------------------+ | | |He's a very naughty boy!| | | +----------------------------+
2.2.5 成员资格
这里用到一个 "in"运算符来检查成员资格,看示例
>>> permissions = 'rw' >>> 'w' in permissions True >>> 'x' in permissions False >>> users = ['mlh','foo','bar'] >>> raw_input('Enter your user name: ') in users Enter your user name: mlh True >>> subject = '$$$ Get rich now!!! $$$' >>> '$$$' in subject True >>>
2_4.py 序列成员资格示例
#检查用户名和PIN码 # -*- coding: cp936 -*- database = [ ['albert','1234'], ['dilbert','4242'], ['smith','7524'], ['jones','9843'] ] username = raw_input('User name: ') pin = raw_input('PIN code: ') if [username, pin] in database: print 'Access granted'
运行效果:
>>> User name: albert PIN code: 1234 Access granted
2.2.6 长度,最小值和最大值
>>> numbers = [100,34,678] >>> len(numbers) 3 >>> max(numbers) 678 >>> min(numbers) 34 >>> max(2,3) 3 >>> min(9,3,2,5) 2