2013-02-04 57 views
0

我有一个包含字符串(从XML提要中提取)的变量。字符串值可以是整数,日期或字符串类型。我需要将它从字符串转换为给定的数据类型。我这样做,但它有点难看,所以我问是否有更好的技术。如果我想检查更多类型,我会以非常嵌套的尝试结束 - 除了块。字符串检查多种类型

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 

谢谢!

+0

又该这个函数返回?它只是检查它是一个int,日期或str,并返回True/False? – Nitzle

+0

返回值并不重要,重点在于是否有更好的解决方案将字符串转换为除嵌套尝试之外的特定数据类型 - 多次除外。如果我要检查4个数据类型,我将有3个级别的try-except块。 – Bruce

回答

5

使用方便的帮手功能。

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) 
0

正确的方法是从xml知道每个应该是什么类型。这将防止发生数字字符串的事情以int结尾,等等。但假设这是不可能的。

对于int类型,我更喜欢

if value.isdigit(): 
    val = int(value) 

的日期,唯一的办法,我能想到会被拆分,并在看的部分,这将是梅西耶然后只是让strptime引发异常。

+2

我绝对不会**更喜欢'尝试 - 除外'。有很多整数,这会失败:''-12''只是一个例子。 “32”是另一个。 – mgilson

+0

@mgilson为什么你会得到'32'?我希望不要转换。是的,我假设负数是无效的。但我发现他们通常是。如果不是......我的不好。 – cmd

+0

但我更喜欢kindall的方法;) – cmd

0
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 val