我有一个包含字符串的变量(从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
Run Code Online (Sandbox Code Playgroud)
谢谢!
使用方便的助手功能.
def tryconvert(value, default, *types):
"""Converts value to one of the given types. The first type that succeeds is
used, so the types should be specified from most-picky to least-picky (e.g.
int before float). The default is returned if all types fail to convert
the value. The types needn't actually be types (any callable that takes a
single argument and returns a value will work)."""
value = value.strip()
for t in types:
try:
return t(value)
except (ValueError, TypeError):
pass
return default
Run Code Online (Sandbox Code Playgroud)
然后编写一个函数来解析日期/时间:
def parsedatetime(value, format="%Y-%m-%d")
return datetime.datetime.striptime(value, format)
Run Code Online (Sandbox Code Playgroud)
现在把它们放在一起:
value = tryconvert(value, None, parsedatetime, int)
Run Code Online (Sandbox Code Playgroud)