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()
for example, this scrpt can output 01/29/1991 to January/29/1991, but I want it output to January,29,1991 How to do it? how to replace the " / " to " , "?
Please don't do it this way; it's already wrong, and can't be fixed without a lot of work. Use datetime.strptime()
to turn it into a datetime
, and then datetime.strftime()
to output it in the correct format.
Take advantage of the datetime module:
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')
就像您替换所有其他字符串一样replace('/',',')
。
You might find a dictionary to be helpful here. It would be "simpler." You could try something as follows.
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]
That will basically get you the same thing in 4 lines of code.
I have just rewrite your code more compact:
m = '01/15/2001'
d = {'01' : 'Jan', '02' : 'Feb'}
for key, value in d.items():
if key in m:
m = m.replace(key, value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.