我有一个变量,其中包含一个字符串(从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:53:17
使用方便的帮助器函数。
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然后编写一个解析日期/时间的函数:
def parsedatetime(value, format="%Y-%m-%d")
return datetime.datetime.striptime(value, format)现在把它们放在一起:
value = tryconvert(value, None, parsedatetime, int)发布于 2013-02-04 23:42:38
正确的方法是从xml中知道每种类型应该是什么。这将防止碰巧是数字字符串的东西以int结尾,等等。但假设这是不可能的。
对于int类型,我更喜欢
if value.isdigit():
val = int(value)对于日期,我能想到的唯一另一种方法是拆分它并查看各个部分,这将比让strptime引发异常更混乱。
发布于 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
复制相似问题