我们主要讨论的是列表和元组2种序列。
(1)索引
0指向第一个字符,-1指向最后一个字符。
例子:
months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December',]
ending = ['st','nd','rd'] + 17 * ['th'] \ + ['st','nd','rd'] + 7 * ['th'] \ + ['st']
year = raw_input("Years:")month = raw_input("Month(1-12):")day = raw_input("Day(1-31):")
month_number = int(month)day_number = int(day)
month_name = months[month_number - 1]ordinal = day + ending[day_number - 1]
print month_name + ' ' + ordinal + ',' + year
(2)分片
可以通过分片操作来访问一定范围内的元素,分片由2个冒号隔开的索引来实现。左边必须大于右边,并且不包含右边。可以通过第三个数值,来指定步进。
例子:
print "URL example 'http://www.baidu.com'"
url = raw_input('Please enter the URL:')domain = url[11:-4]print "Domain name:" + domain
(3)序列相加
>>>[1,2,3] + [4,5,6]
>>>'Hello' + 'World'
注意,列表和字符不能相加。
(4)乘法
>>>'python' * 5
(5)成员资格
用in运算符,检测成员是否在序列中。
例子:
database = [ ['albert','1234'], ['dilbert','4242'], ['smith','7524'], ['jones','9843'], ['buranle','8888']]
username = raw_input("Username:")pin = raw_input("PIN code:")
if [username,pin] in database: print "Access granted"
(6)长度、最小值和最大值
内建函数len、min和max。