How can I check if a string represents an int, without using try/except?
If you're really just annoyed at using try/except
s all over the place, please just write a helper function:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False
It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.
Easiest way to check if a Python string is a number without using try/except?
You can check for None
, instance, and number-like strings:
if not rate or not str(rate).replace(".", "").isnumeric():
rate = 0
elif isinstance(rate, str):
if rate.isnumeric():
rate = int(rate)
elif rate.replace(".", "").isnumeric():
rate = float(rate)
Test table
rate | output | type |
---|---|---|
'test' | 0 | <class 'int'> |
'test123' | 0 | <class 'int'> |
'123' | 123 | <class 'int'> |
None | 0 | <class 'int'> |
False | 0 | <class 'int'> |
123 | 123 | <class 'int'> |
'1.1/1' | 0 | <class 'int'> |
complex(1, 1) | 0 | <class 'int'> |
'1.1' | 1.1 | <class 'float'> |
1.1 | 1.1 | <class 'float'> |
Checking whether a variable is an integer or not
If you need to do this, do
isinstance(<var>, int)
unless you are in Python 2.x in which case you want
isinstance(<var>, (int, long))
Do not use type
. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int
, your new class should register as an int
, which type
will not do:
class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an int
, instead of mandating that it be one.
BUT
The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x
is an integer; assume that it is and catch the exception results if it isn't:
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.
How to check if a variable is an integer or a string?
In my opinion you have two options:
Just try to convert it to an
int
, but catch the exception:try:
value = int(value)
except ValueError:
pass # it was a string, not an int.This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit()
returnsTrue
only if all characters in the string are digits (0
-9
).The
unicode
/ Python 3str
type equivalent isunicode.isdecimal()
/str.isdecimal()
; only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int()
values, as whitespace and +
and -
are also allowed in int()
values. The first form will happily accept ' +10 '
as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
Checking to see if a string is an integer or float
If the string is convertable to integer, it should be digits only. It should be noted that this approach, as @cwallenpoole said, does NOT work with negative inputs beacuse of the '-' character. You could do:
if NumberString.isdigit():
Number = int(NumberString)
else:
Number = float(NumberString)
If you already have Number confirmed as a float, you can always use is_integer
(works with negatives):
if Number.is_integer():
Number = int(Number)
How do I check if a string is a number (float)?
Which, not only is ugly and slow
I'd dispute both.
A regex or other string parsing method would be uglier and slower.
I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.
The issue is that any numeric conversion function has two kinds of results
- A number, if the number is valid
- A status code (e.g., via errno) or exception to show that no valid number could be parsed.
C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.
I think your code for doing this is perfect.
Related Topics
How to Connect to a MySQL Database in Python
Understanding Inplace=True in Pandas
How to Step Through Python Code to Help Debug Issues
Use a List of Values to Select Rows from a Pandas Dataframe
What Does the "At" (@) Symbol Do in Python
Find If 24 Hrs Have Passed Between Datetimes
Difference Between Del, Remove, and Pop on Lists
Do Regular Expressions from the Re Module Support Word Boundaries (\B)
How to Create a List of Random Numbers Without Duplicates
Is There a Standardized Method to Swap Two Variables in Python
Unicodedecodeerror When Reading CSV File in Pandas With Python
How to Remove an Element from a List by Index
Display Number With Leading Zeros
Save Plot to Image File Instead of Displaying It Using Matplotlib