Reputation: 3910
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?
Upvotes: 3
Views: 166
Reputation: 837
If you don't want to write any exception you can go with this code:
our_value = '123' # It can be 'N/A' or 123
if type(our_value ) is str:
if our_value .isdigit():
our_value = int(our_value)
else:
our_value = 0
print(our_value)
If the type is string and its a number then we can apply int() function. If it is int and not a number then it's 'N/A' and converted to 0. If the value is int then there is no need for any conversions.
Upvotes: 1
Reputation: 6891
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.
Upvotes: 3
Reputation: 20490
This will work as well
try:
our_value = int(our_value)
except ValueError:
our_value = 0
Upvotes: 6
Reputation: 2037
This will work:
our_value = int(our_value) if str(our_value).isdigit() else 0
If our_value
will be integer, it would be converted to the string first and if it contains only digits, than it would be converted back to integer.
Upvotes: 0