How do you check in python whether a string contains only numbers?

PythonStringNumbers

Python Problem Overview


How do you check whether a string contains only numbers?

I've given it a go here. I'd like to see the simplest way to accomplish this.

import string

def main():
    isbn = input("Enter your 10 digit ISBN number: ")
    if len(isbn) == 10 and string.digits == True:
        print ("Works")
    else:
        print("Error, 10 digit number was not inputted and/or letters were inputted.")
        main()

if __name__ == "__main__":
    main()
    input("Press enter to exit: ")

Python Solutions


Solution 1 - Python

You'll want to use the isdigit method on your str object:

if len(isbn) == 10 and isbn.isdigit():

From the isdigit documentation:

> str.isdigit() > > Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

Solution 2 - Python

Use str.isdigit:

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

Solution 3 - Python

Use string isdigit function:

>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False

Solution 4 - Python

You can also use the regex,

import re

eg:-1) word = "3487954"

re.match('^[0-9]*$',word)

eg:-2) word = "3487.954"

re.match('^[0-9\.]*$',word)

eg:-3) word = "3487.954 328"

re.match('^[0-9\.\ ]*$',word)

As you can see all 3 eg means that there is only no in your string. So you can follow the respective solutions given with them.

Solution 5 - Python

As pointed out in this comment https://stackoverflow.com/questions/21388541/how-do-you-check-in-python-whether-a-string-contains-only-numbers#comment96723571_21388567 the isdigit() method is not totally accurate for this use case, because it returns True for some digit-like characters:

>>> "\u2070".isdigit() # unicode escaped 'superscript zero' 
True

If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":

import string

def contains_only_digits(s):
    # True for "", "0", "123"
    # False for "1.2", "1,2", "-1", "a", "a1"
    for ch in s:
        if not ch in string.digits:
            return False
    return True

Used in the example from the question:

if len(isbn) == 10 and contains_only_digits(isbn):
    print ("Works")

Solution 6 - Python

What about of float numbers, negatives numbers, etc.. All the examples before will be wrong.

Until now I got something like this, but I think it could be a lot better:

'95.95'.replace('.','',1).isdigit()

will return true only if there is one or no '.' in the string of digits.

'9.5.9.5'.replace('.','',1).isdigit()

will return false

Solution 7 - Python

As every time I encounter an issue with the check is because the str can be None sometimes, and if the str can be None, only use str.isdigit() is not enough as you will get an error

> AttributeError: 'NoneType' object has no attribute 'isdigit'

and then you need to first validate the str is None or not. To avoid a multi-if branch, a clear way to do this is:

if str and str.isdigit():

Hope this helps for people have the same issue like me.

Solution 8 - Python

You can use try catch block here:

s="1234"
try:
    num=int(s)
    print "S contains only digits"
except:
    print "S doesn't contain digits ONLY"

Solution 9 - Python

There are 2 methods that I can think of to check whether a string has all digits of not

Method 1(Using the built-in isdigit() function in python):-

>>>st = '12345'
>>>st.isdigit()
True
>>>st = '1abcd'
>>>st.isdigit()
False

Method 2(Performing Exception Handling on top of the string):-

st="1abcd"
try:
    number=int(st)
    print("String has all digits in it")
except:
    print("String does not have all digits in it")

The output of the above code will be:

String does not have all digits in it

Solution 10 - Python

you can use str.isdigit() method or str.isnumeric() method

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCoder77View Question on Stackoverflow
Solution 1 - PythonmhlesterView Answer on Stackoverflow
Solution 2 - Pythonuser2555451View Answer on Stackoverflow
Solution 3 - PythonndpuView Answer on Stackoverflow
Solution 4 - PythonDevendra BhatView Answer on Stackoverflow
Solution 5 - PythonmitView Answer on Stackoverflow
Solution 6 - PythonJoe9008View Answer on Stackoverflow
Solution 7 - PythonzhihongView Answer on Stackoverflow
Solution 8 - Pythoncold_coderView Answer on Stackoverflow
Solution 9 - PythonRahulView Answer on Stackoverflow
Solution 10 - PythonFaithView Answer on Stackoverflow