Check if a String is a Number Using a Custom is_number()
Function
The following example demonstrates how to create a custom function is_number()
to determine if a string is a number.
Example (Python 3.0+)
def is_number(s): try: float(s) # Try converting to float return True except ValueError: pass try: import unicodedata # Handle Unicode strings unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False # Test with strings and numbers print(is_number('foo')) # False print(is_number('1')) # True print(is_number('1.3')) # True print(is_number('-1.37')) # True print(is_number('1e3')) # True # Test with Unicode characters # Arabic 5 print(is_number('٥')) # True # Thai 2 print(is_number('๒')) # True # Chinese number print(is_number('四')) # True # Copyright symbol print(is_number('©')) # False
Output:
False True True True True True True True False
In this example, the is_number()
function first attempts to convert the string to a float to determine if it’s a valid number. If that fails, it tries using the unicodedata.numeric()
method to handle Unicode representations of numbers.
Additional Methods for Checking Numbers
isdigit()
: This method checks if the string consists only of digits. It does not handle floats or negative numbers.print('123'.isdigit()) # True print('123.45'.isdigit()) # False
isnumeric()
: This method checks if a string contains only numeric characters and works mainly with Unicode objects.print('四'.isnumeric()) # True print('123'.isnumeric()) # True