Python isdigit() function returns false on the float. So you can’t use isdigit with float string in Python.
str.isdigit()
will only return true if all characters in the string are digits. .
is punctuation, not a digit. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal
Python isdigit float example.
A simple example code validates floating numbers in isdigit() in Python.
s = input('Enter the number :')
if s.replace('.', '', 1).isdigit() and '-' not in s:
print('OK to process')
else:
print('not OK to process')
Output:
You can try the conversion and catch any errors
Use exception handling and list comprehension.
def is_float(x):
try:
float(x)
return True
except ValueError:
return False
lis = ['fun', '3.25', '4.222', 'cool', '82.356', 'go', 'foo', '255.224']
res = [x for x in lis if not is_float(x)]
print(res)
To modify the same list object use slice assignment:
lis[:] = [x for x in lis if not is_float(x)]
Use regular expressions
import re
p = re.compile('\d+(\.\d+)?')
a = input('How much is 1 share in that company? ')
while p.match(a) == None:
print("You need to write a number!\n")
a = input('How much is 1 share in that company? ')
Do comment if you have any doubts or suggestions on this Pytohn isdigit topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.