是否有内置或更多 Pythonic 的方法来尝试将字符串解析为整数 [英] Is there a built-in or more Pythonic way to try to parse a string to an integer

查看:22
本文介绍了是否有内置或更多 Pythonic 的方法来尝试将字符串解析为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试将字符串解析为整数时,我必须编写以下函数才能正常失败.我想 Python 有一些内置的东西可以做到这一点,但我找不到它.如果没有,是否有一种不需要单独函数的更 Pythonic 的方法?

def try_parse_int(s, base=10, val=None):尝试:返回 int(s, base)除了值错误:返回值

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

def ignore_exception(exception=Exception, default_val=None):"""返回一个装饰器,它忽略由它的函数引发的异常装饰.将其用作装饰器:@ignore_exception(ValueError)def my_function():经过将其用作函数包装器:int_try_parse = ignore_exception(ValueError)(int)"""定义装饰器(功能):def 包装器(*args, **kwargs):尝试:返回函数(*args, **kwargs)除了例外:返回默认值返回包装器返回装饰器

解决方案

这是一个非常常见的场景,所以我编写了一个ignore_exception"装饰器,适用于各种抛出异常而不是正常失败的函数:

>

def ignore_exception(IgnoreException=Exception,DefaultVal=None):""" 用于忽略函数异常的装饰器例如@ignore_exception(DivideByZero)例如2.ignore_exception(DivideByZero)(Divide)(2/0)"""def dec(函数):def _dec(*args, **kwargs):尝试:返回函数(*args, **kwargs)除了忽略异常:返回默认值返回_dec返回十二月

在您的情况下的用法:

sint = ignore_exception(ValueError)(int)print sint("Hello World") # 不打印打印 sint("1340") # 打印 1340

I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function?

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

The solution I ended up using was a modification of @sharjeel's answer. The following is functionally identical, but, I think, more readable.

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

解决方案

This is a pretty regular scenario so I've written an "ignore_exception" decorator that works for all kinds of functions which throw exceptions instead of failing gracefully:

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

Usage in your case:

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

这篇关于是否有内置或更多 Pythonic 的方法来尝试将字符串解析为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆