How do you check in python whether a string contains only numbers?
Question:
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: ")
Answers:
Use str.isdigit
:
>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>
Use string isdigit function:
>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False
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.
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"
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.
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
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.
As pointed out in this comment How do you check in python whether a string contains only numbers? 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")
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
you can use str.isdigit() method or str.isnumeric() method
You can use this one too:
re.match(r'^[d]*$' , YourString)
Solution:
def main():
isbn = input("Enter your 10 digit ISBN number: ")
try:
int(isbn)
is_digit = True
except ValueError:
is_digit = False
if len(isbn) == 10 and is_digit:
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: ")
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: ")
Use str.isdigit
:
>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>
Use string isdigit function:
>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False
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.
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"
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.
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
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.
As pointed out in this comment How do you check in python whether a string contains only numbers? 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")
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
you can use str.isdigit() method or str.isnumeric() method
You can use this one too:
re.match(r'^[d]*$' , YourString)
Solution:
def main():
isbn = input("Enter your 10 digit ISBN number: ")
try:
int(isbn)
is_digit = True
except ValueError:
is_digit = False
if len(isbn) == 10 and is_digit:
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: ")