For non-negative (unsigned) integers only, use isdigit():
>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
Documentation for isdigit(): Python2, Python3
For Python 2 Unicode strings:
isnumeric().
For non-negative (unsigned) integers only, use isdigit():
>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
Documentation for isdigit(): Python2, Python3
For Python 2 Unicode strings:
isnumeric().
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/except doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.
The issue across programming languages 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 just fine. The only thing that could be cleaner is moving the return True into an else block, to be clear that it's not part of the code under test – not that there's much ambiguity.
def is_number(s):
try:
float(s)
except ValueError: # Failed
return False
else: # Succeeded
return True
Hello everyone,
I have a very simple question.
Let's say you have a list:
'1 1.5 4.56 32'
And you want to separate the integers from the floats into different lists.
E.G.
int_list=[1,32] float_list=[1.5,4.56]
I've tried a variety of things (convert it to a list and use try/except with int, but this only works with the integers, not the floats). Regex (\d+(?!\.)(?<!\.) basically, a digit that doesn't have a decimal before/after it, but this wouldn't work for the numbers past the 2nd decimal point). Only thing I've found is converting the string to an array and using as.type, but I want to do this without using numpy.
Any help would be greatly appreciated!
python - Checking to see if a string is an integer or float - Stack Overflow
How can I check if a string represents an integer?
python - How can I check if a string represents an int, without using try/except? - Stack Overflow
Checking if a string can be converted to float in Python - Stack Overflow
How can I check if a string represents a float in Python?
Is there a built-in Python method to check if a string is a number?
Why is it important to check if a string represents a number before performing mathematical operations?
Videos
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)
Here is the method to check,
a = '10'
if a.isdigit():
print "Yes it is Integer"
elif a.replace('.','',1).isdigit() and a.count('.') < 2:
print "Its Float"
else:
print "Its is Neither Integer Nor Float! Something else"
I tried it with isinstance(<var>, int)
But if the string is: '5', it returns False because it's still a string.
If you write isinstance(int(<var>), int), in some cases it works but when the string is 'abc' the string cannot be casted into an integer and an error pops up. With type() it's the same problem.
With:
try:
int( '7.5')
except:
#code
7.5 can get casted into an integer but it's not an actual integer.
with positive integers you could use .isdigit:
>>> '16'.isdigit()
True
it doesn't work with negative integers though. suppose you could try the following:
>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True
it won't work with '16.0' format, which is similar to int casting in this sense.
edit:
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
If you're really just annoyed at using try/excepts all over the place, please just write a helper function:
def represents_int(s):
try:
int(s)
except ValueError:
return False
else:
return True
>>> print(represents_int("+123"))
True
>>> print(represents_int("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.
I would just use..
try:
float(element)
except ValueError:
print("Not a float")
..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.
Another option would be a regular expression:
import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
print("Not float")
Python3 method to check for float:
def is_float(element: any) -> bool:
#If you expect None to be passed:
if element is None:
return False
try:
float(element)
return True
except ValueError:
return False
Python2 version of the above: How do I parse a string to a float or int?
Always do unit testing. What is and is not a float may surprise you:
Command to parse Is it a float? Comment
-------------------------------------- --------------- ------------
print(isfloat("")) False
print(isfloat("1234567")) True
print(isfloat("1_2_3.4")) True 123.4, underscores ignored
print(isfloat("NaN")) True nan is also float
print(isfloat("123.456")) True
print(isfloat("123.E4")) True
print(isfloat(".1")) True
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777")) True This is same as Inf
print(isfloat("-iNF")) True
print(isfloat("1.797693e+308")) True
print(isfloat("infinity")) True
print(isfloat("1,234")) False
print(isfloat("NULL")) False case insensitive
print(isfloat("NaNananana BATMAN")) False
print(isfloat(",1")) False
print(isfloat("123.EE4")) False
print(isfloat("infinity and BEYOND")) False
print(isfloat("12.34.56")) False Two dots not allowed.
print(isfloat("#56")) False
print(isfloat("56%")) False
print(isfloat("0E0")) True
print(isfloat("x86E0")) False
print(isfloat("86-5")) False
print(isfloat("True")) False Boolean is not a float.
print(isfloat(True)) True Boolean is a float
print(isfloat("+1e1^5")) False
print(isfloat("+1e1")) True
print(isfloat("+1e1.3")) False
print(isfloat("+1.3P1")) False
print(isfloat("-+1")) False
print(isfloat("(1)")) False brackets not interpreted
Sinking exceptions like this is bad, because killing canaries is bad because the float method can fail for reasons other than user input. Do not be using code like this on life critical software. Also python has been changing its contract on what unicode strings can be promoted to float so expect this behavior of this code to change on major version updates.