Check if a String Contains Only Numbers in Python



Python has an in-built function isdigit() which returns true if all characters in a string are digit (between 0-9)

>>> string='9764135408'
>>> string.isdigit()
True
>>> string='091-9764135408'
>>> string.isdigit()
False

You can also use regex expression to check if string contains digits only.

>>> import re
>>> bool(re.match('^[0-9]+$','9764135408'))
True
>>> bool(re.match('^[0-9]+$','091-9764135408'))
False
Updated on: 2020-03-02T10:00:52+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements