Python的新手,已经阅读了很多其他的SO问题,我觉得我错过了一些关于如何按用户输入到字符串格式的东西。我有这个简单的代码,我得到了AttributeError: 'int' object has no attribute 'split'
所以我添加了异常处理,每次都得到错误。 我几乎用str(),datetime()和std.readline()尝试了几乎所有东西。
def dateConverter(userDate):
try:
#split the substrings for month day year
date = userDate.split("/")
#day
day = date[:2]
#month
month = date[3:5]#[ beginning : beginning + LENGTH]
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
for key,value in months:
month=value
#year
year = date[4:]
print(str(month + ' ' + day + ',' + year))
return True
except:
print('Error')
return False
print('Enter a date in the format: mm/dd/yyyy \n')
userInput = raw_input()
dateConverter(userInput)
main()
注意:我在Win7上安装了Python27和Python34 的修改
vaibhav-sagar是正确的,我没有以正确的方式切割字符串,与输入无关。 虽然,我有Python27& Python34安装,即使我设置我的变量路径到Python34我必须使用raw_input(),我听说在Python34中已弃用所以请注意这一点。那就是让我难过的!对不起,这是我对Python的第二次看,所以这是一个非常新的领域。我实际上得到了另一个SO答案的切片示例,这就是我得到的假设。这是解决方案:
#custom date converter func
def dateConverter(userDate):
try:
#split the substrings for month day year
date = userDate.split("/")
#day
day = date[1]#[ beginning : beginning + LENGTH]
#month
month = date[0]
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
month=months[int(month)]
#year
year = date[2]
print(month + ' ' + day + ',' + year)
return True
except:
print('Error')
return False
下一步是使用re验证验证日期是否有效
答案 0 :(得分:1)
我正在使用Python 3.3.5并获得不同的错误。
正在提出异常for key, value in months:
因为迭代字典只产生键,而不是键和值。你想要的是:
for key, value in months.items():
更一般地说,您的问题似乎与您对用户输入的按摩无关。这可以通过使用IDLE或其他REPL来验证。例如:
>>> someDate = '12/10/2014'
>>> date = someDate.split('/')
>>> date
['12', '10', '2014']
>>> day = date[:2]
>>> day
['12', '10']
>>> month = date[3:5]
>>> month
[]
>>> year = date[4:]
>>> year
[]
Python的切片语法正在做一些与我想要的不同的事情。我也认为你不需要for循环,而是你可以这样做:
month = months[int(month)]
这会将月份名称指定为month
,就像您期望的那样。做我认为你想要的功能看起来像这样:
def dateConverter(userDate):
#split the substrings for month day year
date = userDate.split("/")
#day
day = date[1]
#month
month = date[0]
months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
month = months[int(month)]
#year
year = date[2]
print(str(month + ' ' + day + ',' + year))
return True
我希望有所帮助。