If you want a one-liner like you've attempted, go with this:
variable = int(stringToInt) if stringToInt else None
This will assign variable
to int(stringToInt)
only if is not empty AND is "numeric". If, for example stringToInt
is 'mystring'
, a ValueError
will be raised.
To avoid ValueError
s, so long as you're not making a generator expression, use a try-except:
try:
variable = int(stringToInt)
except ValueError:
variable = None
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…