有没有一种内置的或更多的Pythonic方法来尝试将字符串解析为整数

2024-03-29 08:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

当试图将字符串解析为整数时,我必须编写以下函数才能正常地失败。我可以想象Python内置了一些东西来完成这个任务,但是我找不到它。如果不需要,是否有一种更像Python的方法不需要单独的函数?

def try_parse_int(s, base=10, val=None):
  try:
    return int(s, base)
  except ValueError:
    return val

我最终使用的解决方案是修改@sharjeel的答案。以下内容在功能上是相同的,但我认为更具可读性。

def ignore_exception(exception=Exception, default_val=None):
  """Returns a decorator that ignores an exception raised by the function it
  decorates.

  Using it as a decorator:

    @ignore_exception(ValueError)
    def my_function():
      pass

  Using it as a function wrapper:

    int_try_parse = ignore_exception(ValueError)(int)
  """
  def decorator(function):
    def wrapper(*args, **kwargs):
      try:
        return function(*args, **kwargs)
      except exception:
        return default_val
    return wrapper
  return decorator

Tags: 函数basereturnparsedefexceptionitfunction
3条回答
def intTryParse(value):
    try:
        return int(value), True
    except ValueError:
        return value, False

那是Python的方式。在python中,通常使用EAFP样式-请求原谅比请求允许更容易。
这意味着你会先尝试,然后在必要的时候清理干净。

这是一个非常常见的场景,因此我编写了一个“ignore_exception”decorator,它适用于抛出异常而不是优雅地失败的各种函数:

def ignore_exception(IgnoreException=Exception,DefaultVal=None):
    """ Decorator for ignoring exception from a function
    e.g.   @ignore_exception(DivideByZero)
    e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
    """
    def dec(function):
        def _dec(*args, **kwargs):
            try:
                return function(*args, **kwargs)
            except IgnoreException:
                return DefaultVal
        return _dec
    return dec

在您的案例中的用法:

sint = ignore_exception(ValueError)(int)
print sint("Hello World") # prints none
print sint("1340") # prints 1340

相关问题 更多 >