Skip to main content
 首页 » 编程设计

python之在 python 中替换字符串时的奇怪行为

2025年05月04日20落叶无声

我有一个格式为“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 

如您所见,当它找到 October 时,替换似乎没问题,但在循环之外,我再次获得完整的月份名称。我做错了什么?

另一个问题:有没有更短的方法来做到这一点?

请您参考如下方法:

不需要_mapping。如果你使用 datetime.datetime对象,strftime 方法可以为您返回缩写的月份:

import datetime as DT 
 
def short_date(date): 
    date = DT.datetime.strptime(date, '%B %d, %Y') 
    return date.strftime('%b %d, %Y') 
 
print(short_date('October 28, 2010')) 

打印

Oct 28, 2010 

如果您的日期字符串有多种格式,那么您可以使用 dateutil 的 parser.parse 而不是使用 strptime(date, '%B %d, %Y') 解析它们方法。为了获得最大的灵 active ,您最好尽早将日期字符串解析为 datetime.datetime 对象,并尽可能晚地使用 strftime 对其进行格式化。