Python string isnumeric() - How to check if a string is numeric
isnumeric() checks if a string is numeric in Python. For example,
3 as a string is numeric because it can be regarded as an integer.
a1 = '7' a2 = 'xyz' a3 = '3.14' a4 = 'stu2345' b1 = a1.isnumeric() b2 = a2.isnumeric() b3 = a3.isnumeric() b4 = a4.isnumeric() print(b1) # True print(b2) # False print(b3) # False print(b4) # False
3.14 is not numeric by the
isnumeric() though we can convert it to float or Decimal.
from decimal import Decimal a3 = '3.14' f = float(a3) d = Decimal(a3) print(f) # 3.14 print(d) # 3.14
A Number with hyphen or comma is not numeric
A phone number often contain hyphens but it's basically an integer. The Python
isnumeric() doesn't regard it as numeric. In many countries, large numbers are written with commas placed every third digit but its expression is not numeric in the
a1 = '123-456-789' a2 = '1,234,567' b1 = a1.isnumeric() b2 = a2.isnumeric() print(b1) # False print(b2) # False
Note that a number with commas can't be converted to an integer by
a = '1,234,567' b = int(a) # ValueError: invalid literal for int() with base 10: '1,234,567'
The simple way to convert it to an int value is replacing commas with an empty string. But Python
locale module has a method to read it as int. The
locale.atoi() converts a
"numeric" string with commas to an integer.
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') a = '1,234,567' b = locale.atoi(a) print(b) # 1234567
Before using this function, you should set the locale information as above.