关于Python脚本的问题!

时间:2010-11-13 19:15:13

标签: python

m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
def main():
    if '01' in m:
        n = m.replace('01','Janauary')
        print n
    elif '02' in m:
        n = m.replace('02','February')
        print n
    elif '03' in m:
        n = m.replace('03','March')
        print n
    elif '04' in m:
        n = m.replace('04','April')
        print n
    elif '05' in m:
        n = m.replace('05','May')
        print n
    elif '06' in m:
        n = m.replace('06','June')
        print n
    elif '07' in m:
        n = m.replace('07','July')
        print n
    elif '08' in m:
        n = m.replace('08','August')
        print n
    elif '09' in m:
        n = m.replace('09','September')
        print n
    elif '10' in m:
        n = m.replace('10','October')
        print n
    elif '11' in m:
        n = m.replace('11','November')
        print n
    elif '12' in m:
        n = m.replace('12','December')
        print n

main()

例如,这个scrpt可以输出01/29/1991到1991年1月29日,但我希望它输出到1月29,1991如何做?如何将“/”替换为“,”?

5 个答案:

答案 0 :(得分:11)

请不要这样做;它已经错了,没有大量的工作就无法修复。使用datetime.strptime()将其变为datetime,然后datetime.strftime()以正确格式输出。

答案 1 :(得分:2)

利用datetime模块:

m = raw_input('Please enter a date(format:mm/dd/yyyy)')

# First convert to a datetime object
dt = datetime.strptime(m, '%m/%d/%Y')

# Then print it out how you want it
print dt.strftime('%B,%d,%Y')

答案 2 :(得分:1)

就像你替换所有其他字符串一样 - replace('/',',')

答案 3 :(得分:0)

您可能会在这里找到一本有用的词典。它会“更简单”。您可以尝试以下内容。

m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
month_dict = {"01" : "January", "02" : "February", "03" : "March", ...}
# then when printing you could do the following
date_list = m.split("/") # This gives you a list like ["01", "21", "2010"]
print(month_dict[date_list[0]] + "," + date_list[1] + "," + date_list[2]

这基本上会让你在4行代码中得到同样的东西。

答案 4 :(得分:0)

我刚刚重写了你的代码:

m = '01/15/2001'
d = {'01' : 'Jan', '02' : 'Feb'}

for key, value in d.items():
   if key in m:
       m = m.replace(key, value)