Computer >> Computer tutorials >  >> Programming >> Python

How to check if a string contains only decimal characters?


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