49

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?

2

6 Answers 6

76

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 stringToInt is not empty AND is "numeric". If, for example stringToInt is 'mystring', a ValueError will be raised. If stringToInt is empty (''), it will assign variable to None.

To avoid ValueErrors, use a try-except:

try:
    variable = int(stringToInt)
except ValueError:
    variable = None
Sign up to request clarification or add additional context in comments.

3 Comments

@kadee if stringToInt is 0 then it is not a string. You're right though, that the one-liner will only work for strings, which was what the question was asking about. Also, your proposed solution wouldn't work for empty strings and would raise the same exception OP was receiving. =)
@kadee stringToInt will never be None because it's a string, as explained in the question.
I don't see how generator expressions are relevant, so I edited and removed that part of this answer, but correct me if I'm wrong.
31

I think this is the clearest way:

variable = int(stringToInt) if stringToInt.isdigit() else None

5 Comments

This won't work where stringToInt is None as that doesn't have an isdigit()
You can strengthen it with check for None like variable = int(stringToInt) if stringToInt and stringToInt.isdigit() else None
isdigit is unsafe because it recognizes unicode power-of-2, ² , as a digit. isdecimal is the safe way. So: variable = int(stringToInt) if stringToInt and stringToInt.isdecimal() else None
This doesn't work for negative numbers like '-1' or strings containing whitespace like ' 1', which int is perfectly capable of parsing. .isdigit() returns false, so you get None. Instead, I'd recommend try-except as in Rob's answer.
@Damian stringToInt is a string, as explained in the question
22

Use the fact that it generates an exception:

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

This has the pleasant side-effect of binding variable to None for other common errors: stringToInt='ZZTop', for example.

4 Comments

I think this solution is probably the best as it will handle situations where the string contains non-digit characters as well.
Doesn't handle None, as calling int() on it raises another exception: "TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'"
@Nickolay stringToInt is supposed to be a string, as explained in the question.
This probably a very common solution, but it actually hides the possibly wanted exception in case the converted value is not a string containing int or None. In a strictly typed application, you wouldn't want to hide this exception.
7

this will parse stringToInt to int if it's valid and return original value if it's '' or None

variable = stringToInt and int(stringToInt)

2 Comments

I quite like the simplicity and elegance of this answer. Although I'm afraid it's a bit less readable than this one, because many Python programmers aren't familiar with the exact semantics of and / or: The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
And it has a drawback (as mentioned by the author) that if stringToInt is "", the empty string is returned instead of None.
3

Here are some options:

Catch the exception and handle it:

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

It's not really that exceptional, account for it:

variable = None
if not stringToInt.isdigit():
    variable = int(stringtoInt)

3 Comments

You don't need the all(). if stringToInt.isdigit(): is sufficient.
Wow, not my day. Certainly not my best answer. I corrected it, but I'm resisting the urge to delete my answer as my penance.
.isdigit() doesn't work for negative numbers like '-1' or strings containing whitespace like ' 1', which int is perfectly capable of parsing.
0

In addition to the other answers, it can also be a TypeError if stringToInt is None. You can catch it like this:

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

5 Comments

Why would stringToInt be None? The question says it's a string. I've noticed a lot of people making the same mistake, so is there something about the question that's confusing?
@wjandrea nowhere in the question does it specify the type of stringToInt. In any case it's common situation on stackoverflow when a random question becomes popular due to search engine ranking and people stumbling on edge-cases the original asker didn't consider try to help fellow googlers by adding information they wished they'd found here. Not sure what you're trying to achieve by commenting we're all wrong all over the place.
@Nickolay "nowhere in the question does it specify the type of stringToInt." - The question clearly says: "Python String to Int Or None" ... "if the string is empty set to None" ... "if the string is empty it will error". If people have the answer to a different question, they're welcome to post it on a separate question (even post one themselves) and link it here in a comment so that people searching for the same thing in the future can find it. They're also welcome to edit the question to clarify and avoid confusion, if there's anything to clarify.
@wjandrea "String" is not a type though. All of str, bytes, Optional[str | bytes] can be colloquially named a "string", as you can judge from the activity of the people on this page.
@Nickolay "String" almost always means str. See the docs for example: "Textual data in Python is handled with str objects, or strings." Including bytes too is fine since there's historical precedent from Python 2 and in this context it works the same as str (e.g. int(b'1')1). I'm pretty sure people are misinterpreting the question, like maybe "convert string to int, but if it's None, leave it as None".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.