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

问题描述 投票:0回答:11

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

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
python parsing integer
11个回答
61
投票

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

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

47
投票
def intTryParse(value):
    try:
        return int(value), True
    except ValueError:
        return value, False

47
投票

实际上有一个“内置”,单行解决方案,不需要引入辅助函数:

>>> s = "123"
>>> i = int(s) if s.isdecimal() else None
>>> print(i)
123

>>> s = "abc"
>>> i = int(s) if s.isdecimal() else None
>>> print(i)
None

>>> s = ""
>>> i = int(s) if s.isdecimal() else None
>>> print(i)
None

>>> s = "1a"
>>> i = int(s) if s.isdecimal() else None
>>> print(i)
None

另请参阅 https://docs.python.org/3/library/stdtypes.html#str.isdecimal


25
投票

这就是Pythonic方式。在Python中,习惯上使用EAFP风格——请求宽恕比请求许可更容易。
这意味着您会先尝试,然后在必要时清理混乱。


16
投票

我会选择:

def parse_int(s, base=10, val=None):
 if s.isdigit():
  return int(s, base)
 else:
  return val

但或多或少是一样的。


7
投票

不,它已经很完美了。不过,将

val
参数命名为 default 会更好。

在官方文档中简单记录为 int(x) -- x 转换为整数


2
投票

int() 是内置的 Python 方式,就像你在那里一样。

直接使用它通常更容易、更常见:

def show_square(user_input):
  """Example of using int()."""
  try:
    num = int(user_input, 10)
  except ValueError:
    print "Error" # handle not-an-integer case
    # or you may just want to raise an exception here
    # or re-raise the ValueError
  else:
    print "Times two is", num * 2

def another_example(user_input):
  try:
    num = int(user_input, 10)
  except ValueError:
    num = default
  print "Times two is", num * 2

2
投票
myList = ['12', '13', '5', 'hope', 'despair', '69','0', '1.2']

myInts = [int(x) for x in myList if x.isdigit()]

1
投票

这可能是将字符串解析为 int 的另一种选择

while True:
try:
    n = input("Please enter an integer: ")
    n = int(n)
    break
except ValueError:
    print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")

0
投票

根据具体情况,以下内容可能适合读者的某些需求;利用短路,它返回 False 或实际整数。

s.isdecimal() and s.isdigit() and int(s)

-3
投票
def parseint(string):
    result = '0'
    for x in string:
        if x.isdigit():
        result+=x
    else:
        return int(result)
    return int(result)
© www.soinside.com 2019 - 2024. All rights reserved.