# How to check if a string contains only decimal characters?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. You can call it as follows:

>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False

But this would fail for floating-point numbers. We can use the following method for those numbers:

def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
isfloat('12.345')
isfloat('12a')
This will give the output:
True
False

You can also use regexes for the same result. For matching decimals, we can call the re.match(regex, string) using the regex: "^\d+?\.\d+?$". For example, >>> bool(re.match("^\d+?\.\d+?$", '123abc'))
False
>>> bool(re.match("^\d+?\.\d+?\$", '12.345'))
True
Updated on 30-Sep-2019 06:54:19