Python如何从索引1开始?查找月份的功能

时间:2018-08-05 23:32:30

标签: python python-3.x

我正在尝试创建一个函数,该函数将为我提供以下所有错误消息,请问有什么方法可以使索引从1开始?

def getMonth(month):
    try:
        list_of_month_index0 = ['Jan', 'Feb','March','April','May','June','July','Aug','Sep','Oct','Nov','Dec']
        return list_of_month_index0[month]
    except IndexError:
            return 'ERROR: out of range!'
    except :
            return 'ERROR: invalid number!'

getMonth('a') # 'ERROR: invalid number!'
getMonth(13) # ERROR: out of range!
getMonth(1) # Jan
getMonth(0) # ERROR: out of range!

3 个答案:

答案 0 :(得分:2)

你出1分了,对吧?因此,将索引更改为1:

# ...

FEED_EXPORT_ENCODING = 'utf-8'

FEED_EXPORTERS = {
    'csv': 'my_scraper.exporters.MyCsvItemExporter',
}

CSV_DELIMITER = ';'

答案 1 :(得分:2)

calendar模块中,标准库已经包含月份名称,这些名称收集在十三个元素的列表中,并且以空字符串作为初始元素。

  

calendar.month_abbr

     

一个数组,表示当前语言环境中一年中的缩写月份。遵循一月份的常规惯例是月份   数字1,因此长度为13,month_abbr [0]为空   字符串。

({calendar.month_name包含未缩写的名称)。

如果您不介意将某些布尔逻辑与try / except结构混合,则可以在函数中使用此数组。

>>> def get_month(month):
...     OUT_OF_RANGE = 'ERROR: out of range!'
...     try:
...         m = calendar.month_abbr[month]
...     except IndexError:
...         return OUT_OF_RANGE
...     except TypeError:    
...     # if _month_ isn't an integer you'll get a TypeError.
...         return 'ERROR: invalid number!'
...     # If the input is zero, m is the empty string, which evaluates to
...     # False in a boolean context, so the error message is returned.
...     return m or OUT_OF_RANGE  
... 
>>> get_month('a')
'ERROR: invalid number!'
>>> get_month('13')
'ERROR: invalid number!'
>>> get_month(1)
'Jan'
>>> get_month(0)
'ERROR: out of range!'

答案 2 :(得分:0)

def getMonth(month):
    try:
        list_of_month= ['Jan', 'Feb','March','April','May','June','July','Aug','Sep','Oct','Nov','Dec']
        if month<1 or month>12:
            raise IndexError('ERROR: out of range!')
        else:
            return list_of_month[month - 1]
    except IndexError as x:
        return '{0}'.format(x)
    except:
        return 'ERROR: invalid number!'
相关问题