我有一个变量,其中包含一个字符串(从XML提要中提取)。字符串值可以是整数、日期或字符串类型。我需要将它从字符串转换为给定的数据类型。我是这样做的,但是有点难看,所以我在问有没有更好的技术。如果我要检查更多的类型,我将以非常嵌套的try - except块结束。
def normalize_availability(self, value):
"""
Normalize the availability date.
"""
try:
val = int(value)
except ValueError:
try:
val = datetime.datetime.strptime(value, '%Y-%m-%d')
except (ValueError, TypeError):
# Here could be another try - except block if more types needed
val = value谢谢!
发布于 2013-02-04 23:49:17
def normalize_availability(value):
"""
Normalize the availability date.
"""
val = value
try:
val = datetime.datetime.strptime(value, '%Y-%m-%d')
except (ValueError):
if value.strip(" -+").isdigit():
val = int(value)
return valhttps://stackoverflow.com/questions/14689959
复制相似问题