# Python technique: using isnumeric instead of numeric exception handling

Implement Python code, input a number, and output three times that number.

``````>>> n = input("Enter a number: ")
Enter a number: 6
>>> print(f"{n} * 3 = {n*3}")
6 * 3 = 666
``````

The input function always returns a string. You can convert strings to integers by int:

``````>>> n = int(n)
>>> print(f"{n} * 3 = {n*3}")
6 * 3 = 18
``````

However, if the input is not a value, an error will be reported:

``````Enter a number: abcd
ValueError: invalid literal for int() with base 10: 'abcd'
``````

A common approach is to run the transformation in a "try" block and catch any exceptions we might get. But the isdigit method of strings can solve this problem more elegantly.

``````>>> '1234'.isdigit()
True
>>> '1234 '.isdigit()  # space at the end
False
>>> '1234a'.isdigit()  # letter at the end
False
>>> 'a1234'.isdigit()  # letter at the start
False
>>> '12.34'.isdigit()  # decimal point
False
>>> ''.isdigit()   # empty string
False
``````

str.isdigit returns True for the regular expression '^ \ d + \$'.

``````>>> n = input("Enter a number: ")
>>> if n.isdigit():
n = int(n)
print(f"{n} * 3 = {n*3}")
``````

Python also includes another method, str.isnumeric. What's the difference between them?

``````>>> n = input("Enter a number: ")
>>> if n.numeric():
n = int(n)
print(f"{n} * 3 = {n*3}")
``````

str.isdigit returns True when the string contains only numbers 0-9. str.isnumeric can also recognize the value of English unexpected language.

``````>>> 'One two three four five'.isdigit()
False
>>> 'One two three four five'.isnumeric()
True
>>> int('Two')
ValueError: invalid literal for int() with base 10: 'Two'
``````

str.isdecimal

``````>>> s = '2²'    # or if you prefer, s = '2' + '\u00B2'
>>> s.isdigit()
True
>>> s.isnumeric()
True
>>> s.isdecimal()
False
``````

Tags: Python

Posted on Mon, 02 Dec 2019 09:55:57 -0800 by rkm11