如何在python中用字符串中的字母打印值的索引?

时间:2013-10-17 05:55:05

标签: python string list

我有:

* MONTHS =(“1月”,“2月”,“3月”,......“12月”)(包括所有月份)

我应该输入一个月的3个字母缩写并获得该月份的索引值。到目前为止,我有:

for M in MONTHS:
    shortMonths = M[0:3]
    print shortMonths
  

1月2月3月4月5月6月7月8月9月10月11月11月

我注意到shortMonths中的输出月份没有引号,这使得无法测试缩写是否为shortMonths:

  

MMM =“二月”

     

打印列表(shortMonths).index(MMM)+ 1#考虑到列表的第一个月,1月,是月0 + 1 = 1,依此类推所有月份

     
    
      

ValueError:'Feb'不在列表中

    
  

如何在不创建功能的情况下解决此问题? 此外,这是一个任务问题。并且,我们不允许使用词典或地图或日期时间

5 个答案:

答案 0 :(得分:1)

听起来你希望shortMonths成为一个列表,但你只是为它分配了一个字符串。

我想你想要这样的东西:

shortMonths = [] # create an empty list
for M in MONTHS:
    shortMonths.append(M[0:3]) # add new entry to the list
print shortMonths # print out the list we just created

或使用列表理解

# create a list containing the first 3 letters of each month name
shortMonths = [M[0:3] for M in MONTHS]
print shortMonths # print out the list we just created

答案 1 :(得分:0)

shortMonths是字符串而不是列表。请执行以下操作。

shortMonths = []
  for M in MONTHS:
    shortmonths.append(M[0:3])

答案 2 :(得分:0)

>>> months = ["January", "Febuary", "March", "April"]
>>> search = "Mar"
>>> [i for i, mo in enumerate(months) if search == mo[0:3]][0]
2
>>> search = "Fan"
>>> [i for i, mo in enumerate(months) if search == mo[0:3]][0]
IndexError: list index out of range

答案 3 :(得分:0)

很简单:

>>> months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
>>> search = "Jan"
>>> months.index([i for i in months if i[:3].lower() == search.lower()][0])+1
1
>>> # Or
... def getmonth(search):
...    for i in months:
...        if i[:3].lower() == search.lower():
...            return x.index(i)+1
>>> getmonth("Feb")
2

捕获错误:

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
while True:
    search = ""
    while len(search) != 3:
        search = raw_input("Enter first 3 letters of a month: ")[:3]
    month = [i for i in months if i[:3].lower() == search.lower()]
    if not month: # Not in the list, empty list: []
        print "%s is not a valid abbreviation!"%search
        continue
    print months.index(month[0])+1

答案 4 :(得分:0)

abbr = raw_input("Enter the month abbr:")


months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
months_abbr = [month.lower()[:3] for month in months]
index = months_abbr.index(abbr.lower())
if index >= 0:
    print "abbr {0} found at index {1}".format(abbr, index)
else:
    print "abbr {0} not found".format(abbr)