开发者

Test if value is Decimal

开发者 https://www.devze.com 2022-12-22 08:57 出处:网络
In some Python (v3) code I am creating lists of Decimals from user input, like this: input = [] # later populated with strings by user with values like \'1.45984开发者_高级运维000E+001\'

In some Python (v3) code I am creating lists of Decimals from user input, like this:

input = [] # later populated with strings by user with values like '1.45984开发者_高级运维000E+001'
decimals = [Decimal(c) for c in input]

However, sometimes the input list contains strings that cannot be parsed. How can I test if c can be represented as a decimal before calling the constructor?


Catch exception

decimals = []
for s in input:
    try: decimals.append(Decimal(s))
    except InvalidOperation:
        pass

Use helper function

from itertools import imap

def parse_decimal(s):
    try: return Decimal(s)
    except InvalidOperation:
        return None

decimals = [d for d in imap(parse_decimal, input) if d is not None]


Don't. Catch the exception thrown by the constructor. If that means turning the list comprehension into a for loop then so be it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号