我有一个格式为“2010 年 10 月 28 日”(或类似)的日期。现在我想将月份的全名更改为更短的版本(在本例中为 Oct)。为此,我准备了一本字典:
_mapping = {'January': 'Jan',
'February': 'Feb',
'March': 'Mar',
'April': 'Apr',
'May': 'May',
'June': 'Jun',
'July': 'Jul',
'August': 'Aug',
'September': 'Sep',
'October': 'Oct',
'November': 'Nov',
'December': 'Dec'}
在替换的方法中,我写了以下内容:
def fetch(self, pno):
...
date = #get data (working fine)
for l, s in self._mapping.iteritems():
pubdate = date.replace(l, s)
print l + " -> " + pubdate #this is only for debug
(pubd_month, self.pubd_day, self.pubd_year) = pubdate.split(' ')
print pubd_month, self.pubd_day, self.pubd_year
print pubdate
执行结果是:
February -> October 28, 2008
October -> Oct 28, 2008
January -> October 28, 2008
April -> October 28, 2008
November -> October 28, 2008
March -> October 28, 2008
August -> October 28, 2008
May -> October 28, 2008
December -> October 28, 2008
June -> October 28, 2008
September -> October 28, 2008
July -> October 28, 2008
October
October 28, 2008
正如你所看到的,当它找到十月时,替换似乎没问题,但在循环之外我又得到了完整的月份名称。我做错了什么?
另一个问题:有没有更短的方法来做到这一点?