Python String to Int Or None

python int
how to convert object to int in python
add none to int python
python string to long
python none
python empty string to int
python convert string to int if possible
python cast to int

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?

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

How to convert Nonetype to int or string?, int(value or 0). This will use 0 in the case when you provide any value that Python considers False , such as None, 0, [], "", etc. Since 0 is False� Now that you have some foundational knowledge about how to represent integers using str and int, you’ll learn how to convert a Python string to an int. Converting a Python String to an int. If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just pass the string to int(), which

I think this is the clearest way:

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

How to Convert a Python String to int – Real Python, There are several ways to represent integers in Python. In this quick and practical tutorial, you'll learn how you can store integers using int and� int(value or 0) This will use 0 in the case when you provide any value that Python considers False, such as None, 0, [], “”, etc. Since 0 is False, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value). int(0 if value is None else value) This replaces only None with 0.

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.

2. Built-in Functions — Python 3.4.10 documentation, As repr(), return a string containing a printable representation of an object, but If function is None, the identity function is assumed, that is, all elements of� The original list is : ['Geeks', None, 'CS', None, None] The list after conversion of None values : ['Geeks', '', 'CS', '', ''] Method #2 : Using str() Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which

Here are some options:

Catch the exception and handle it:

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

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

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

How to convert a NoneType to an integer or string in Python, NoneType is the type for the None object which represents no value. Converting a NoneType to an integer or string creates a new replacement value for None . I've got an Nonetype value x, it's generally a number, but could be None. I want to divide it by a number, but Python raises: TypeError: int() argument must be a string or a number, not 'NoneType' How can I solve this? In one of the comments, you say: Somehow I got an Nonetype value, i

Python String to Int, Int to String, If the string you want to convert into int belongs to different number base other that base 10, you can specify the base for conversion. But remember that the output� Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)

Python String to Int: How to Convert a String to an Integer in Python, Unlike many other programming languages out there, Python does not implicitly typecast integers (or floats) to strings when you concatenate� Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Type hints cheat sheet (Python 3) — Mypy 0.782 documentation, This is how you declare the type of a variable type in Python 3.6 age: int = 1 # In some_function() # Mypy understands a value can't be None in an if-statement if x If you use the string literal 'A', it will pass as long as there is a # class of that� @BallpointBen I think the key point is that Python possesses a strong concept of object identity. If you want to check whether an object compares equal to None, by all means use obj == None. If you want to check whether an object is None, use obj is None.

Comments
  • Define 'empty'? Is ' ' empty? Any white space?
  • This is almost the reverse question to Python: most idiomatic way to convert None to empty string?
  • This bears explanation in detail for a novice.
  • The one-liner returns None when stringToInt = 0. Better would be: variable = int(stringToInt) if stringToInt is not None else None.
  • @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. =)
  • 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
  • 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'"
  • 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.