Python String isdigit() Method Tutorial

Python provides the isdigit() method in order to check if the given string completely consists of numbers and can be converted into the number without any problem. In this tutorial we will learn how to use the isdigit() method to check and validate if a given string is a number.

isdigit() Method Syntax

isdigit() method has very simple syntax. It has no parameter and returns True or False boolean value according to the check result. If the specified string is a valid digit returns True. If specified string is not valid digit returns False.

val.isdigit()
  • val is a string which contains single or multiple characters.

Check String

We will check the specified string if all of its characters are a digit() with the isdigit() method.

a = "21212"

b = "1212!"

c = "3e4r1q"

d = "54.62"

e = "54 62 75"

print( a.isdigit() )

print( b.isdigit() )

print( c.isdigit() )

print( d.isdigit() )

print( e.isdigit() )

print( "[email protected]".isdigit() )

print( "-1231".isdigit() )

print( "-12.34".isdigit() )

Check Unicode String If Digit

Strings can consist of single or multiple characters and can be expressed with different encoding formats. Unicode is another encoding format that can be directly used in Python to create a string. In the following part, we will check different Unicode strings if they are digit.

a = "\u0030"

b = "\u0030"

#Superscript 
c = "\u00B23455"

#Fraction
d = "\u00B23455"

print( a.isdigit() )

print( b.isdigit() )

print( c.isdigit() )

print( d.isdigit() )

Check Unicode String If Digit

NumPy isdigit() Method

NumPy 3rd party Python library also provides isdigit() method. It is provided under the numpy.char module. You can use this method the same as the native Python isdigit() method too. The only difference is that as a 3rd party module the specified string is provided as a parameter to the numy.char.is.digit() method.

import numpy

a = "21212"

b = "1212!"

c = "3e4r1q"

d = "54.62"

e = "54 62 75"

print( numpy.char.isdigit(a) )

print( numpy.char.isdigit(b) )

print( numpy.char.isdigit(c) )

print( numpy.char.isdigit(d) )

print( numpy.char.isdigit(e) )

print( numpy.char.isdigit("[email protected]") )

print( numpy.char.isdigit("-1231") )

print( numpy.char.isdigit("-12.34") )
NumPy isdigit() Method

isdigit() Conditions

isdigit() check different conditions and returns the result accordingly. Below we will list all these conditions.

  • White space interpreted as letter and returns False.
  • Alphabet interpreted as letter and returns False.
  • Special characters interpreted as not digit and returns False.
  • Decimals interpreted as no digit and returns False.
  • Empty String interpreted as letter and return False.

Leave a Comment