列表与元组——索引

序列中所有的元素都是有编号的——从0开始递增
greeting = 'Hello'
greeting[0]
Out[7]: 'H'
这就是索引,可以通过索引获取元素,所有序列都可以通过这种方式进行索引。使用负数索引,python会从右边,也就是最后1个元素开始计数。最后一个元素的位置编号是-1.
greeting[-1]
Out[8]: 'o'

'Hello'[1]
Out[9]: 'e'

fourth = raw_input('Year: ')[3]

Year: 2017

fourth
Out[11]: '7'


例子:
months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
]
endings = ['st','nd','rd'] + 17 *['th'] \
         + ['st','nd','rd'] + 7 * ['th'] \
         + ['st']
year     =raw_input('Year: ')
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 + endings[day_number-1]
print month_name + ' ' + ordinal + ', '+year

你可能感兴趣的:(python编程,python基础知识)