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!
How to differentiate between a float and an integer in a string
How can I check if a string represents an integer?
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"