Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python determine whether variable is number when can be string or int?

Tags:

python

I have variable passed in which can be a string or integer passed in. For example it can be '123' or 123. Additionally, it could be a string like 'N/A', and in this case I want to replace it with 0.

I have been trying to do something like this:

our_value = int(our_value) if our_value.isdigit() else 0

The issue is when our_value is an integer it has no method isdigit. If it's a string this will work fine.

How can I handle both cases where it can be a integer or string?

like image 760
William Ross Avatar asked Nov 30 '25 04:11

William Ross


2 Answers

This will work as well

try:
    our_value = int(our_value)
except ValueError:
   our_value = 0
like image 124
Devesh Kumar Singh Avatar answered Dec 02 '25 16:12

Devesh Kumar Singh


To avoid double conversions it is possible to use a try/except construction such as:

try:
    our_value = int(our_value)
except ValueError:
    our_value = 0

In this case, we try to coerce the value to an integer. This will be successful if we have an integer already, or a string that can be interpreted as an integer.

Other strings will fall into our except case and thereby set to 0.

like image 42
JohanL Avatar answered Dec 02 '25 17:12

JohanL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!