Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

Python String to Int Or None

Learning Python and a little bit stuck.

I'm trying to set a variable to equal int(stringToInt) or if the string is empty set to None.

I tried to do variable = int(stringToInt) or None but if the string is empty it will error instead of just setting it to None.

Do you know any way around this?

question from:https://stackoverflow.com/questions/18623668/python-string-to-int-or-none

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ValueErrors, so long as you're not making a generator expression, use a try-except:

try:
    variable = int(stringToInt)
except ValueError:
    variable = None

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...