Chr*_*alo 55 python parsing integer
在尝试将字符串解析为整数时,我必须编写以下函数才能正常失败.我认为Python内置了一些内容来做到这一点,但我找不到它.如果没有,是否有更多的Pythonic方式,不需要单独的功能?
def try_parse_int(s, base=10, val=None):
try:
return int(s, base)
except ValueError:
return val
Run Code Online (Sandbox Code Playgroud)
我最终使用的解决方案是修改了@ 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
Run Code Online (Sandbox Code Playgroud)
sha*_*eel 46
这是一个非常常规的场景,所以我编写了一个"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
Run Code Online (Sandbox Code Playgroud)
用法:
sint = ignore_exception(ValueError)(int)
print sint("Hello World") # prints none
print sint("1340") # prints 1340
Run Code Online (Sandbox Code Playgroud)
Luk*_*kas 26
def intTryParse(value):
try:
return int(value), True
except ValueError:
return value, False
Run Code Online (Sandbox Code Playgroud)
Lar*_*erg 12
实际上有一个不需要引入新功能的“内置”单行解决方案。因为我希望在这里找到这样的答案,所以我添加了它:
>>> s = "123"
>>> i = int(s) if s.isdigit() else None
>>> print(i)
123
>>> s = "abc"
>>> i = int(s) if s.isdigit() else None
>>> print(i)
None
>>> s = ""
>>> i = int(s) if s.isdigit() else None
>>> print(i)
None
>>> s = "1a"
>>> i = int(s) if s.isdigit() else None
>>> print(i)
None
Run Code Online (Sandbox Code Playgroud)
另见https://docs.python.org/3/library/stdtypes.html#str.isdigit
我会去:
def parse_int(s, base=10, val=None):
if s.isdigit():
return int(s, base)
else:
return val
Run Code Online (Sandbox Code Playgroud)
但它或多或少都是一样的.
不,它已经很完美了.但是,该val参数可以更好地命名为default.
在官方文档中记录为int(x) - x转换为整数