Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

How can I check if a string can be converted to a number?

  • isdecimal

  • isnumeric

  • This solution only works for integers. Not for floating point numbers.

  • We'll talk about this later. For now assume that the user enters something that can be converted to a number.

  • Wrap the code in try-except block to catch any exception raised during the conversion.

  • Use Regular Expressions (regexes) to verify that the input string looks like a number.

  • Unicode Characters in the 'Number, Decimal Digit' Category

  • isdecimal Decimal numbers (digits) (not floating point)

  • isnumeric Numeric character in the Unicode set (but not floating point number)

  • In your spare time you might want to check out the standard types of Python at stdtypes.

val = input("Type in a number: ")
print(val)
print(val.isdecimal())
print(val.isnumeric())

if val.isdecimal():
    num = int(val)
    print(num)
Type in a number: 42
42
True
True
42
Type in a number: 4.2
4.2
False
False

val = '11'
print(val.isdecimal()) # True
print(val.isnumeric()) # True

val = '1.1'
print(val.isdecimal()) # False
print(val.isnumeric()) # False

val = '٣'  # arabic 3
print(val.isdecimal()) # True
print(val.isnumeric()) # True
print(val)
print(int(val))  # 3

val = '½' # unicode 1/2
print(val.isdecimal()) # False
print(val.isnumeric()) # True
# print(float(val))  # ValueError: could not convert string to float: '½'

val = '②' # unicode circled 2
print(val.isdecimal()) # False
print(val.isnumeric()) # True
# print(int(val)) # ValueError: invalid literal for int() with base 10: '②'