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)
Answer from francisco sollima on Stack OverflowIf 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"
How to differentiate between a float and an integer in a string
Checking if a string can be converted to float in Python - Stack Overflow
How do I check for a float?
python - How do I check if a string represents a number (float or int)? - 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
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!
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.
while True:
while True:
print("Enter a number")
num1 = input("")
if (num1.isfloat()):
break
else:
continue
while True:
print("Enter a second number")
num2 = input("")
if (num2.isfloat()):
break
else:
continue
For context. I'm writing a super simple, two number calculator. And i wanted to write a section where it tests for a float. So when you type in a number, for number 1 (the variable is called num1), python is suppose to check if it is a float or not. And if it it, it will continue the script if it is. And ask for the number again if its not. However, I'm struggling to find the right syntax to check for a float. isdigit and numeric work, but for some reason isfloat() does not work for me. What am I typing wrong, I'm quite new to programming.
User helper function:
def if_ok(fn, string):
try:
return fn(string)
except Exception as e:
return None
then
if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])
def is_float(s):
if s is None:
return False
if len(s) == 0:
return False
digits_count = 0
dots_count = 0
signs_count = 0
for c in s:
if '0' <= c <= '9':
digits_count += 1
elif c == '.':
dots_count += 1
elif c == '-' or c == '+':
signs_count += 1
else:
return False
if digits_count == 0:
return False
if dots_count > 1:
return False
if signs_count > 1:
return False
return True
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.