是否有一种内置的或更多的 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
68064 次浏览

int() is the built-in and pythonic way, just like you have there.

It's usually easier and more common to use it directly though:

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

No, it is already perfect. The val parameter could be better named default, though.

Documented in the official docs simply as int(x) -- x converted to integer

I would go for:

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

But it's more or less the same thing.

That's the pythonic way. In python, it's customary to use EAFP style - Easier to Ask Forgiveness than Permission.
That means you'd try first, and then clean up the mess if necessary.

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
def intTryParse(value):
try:
return int(value), True
except ValueError:
return value, False
def parseint(string):
result = '0'
for x in string:
if x.isdigit():
result+=x
else:
return int(result)
return int(result)
myList = ['12', '13', '5', 'hope', 'despair', '69','0', '1.2']


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

This could be another alternative for parsing string to 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!")

Actually there is a "built-in", single line solution that doesn't require to introduce a new function. As I hoped to find such an answer here, I'm adding it:

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

See also https://docs.python.org/3/library/stdtypes.html#str.isdecimal