Python String isnumeric() Function
The String isnumeric()
method returns True
if the string is not empty and all the characters are numeric characters. Otherwise, it returns False
.
Numeric characters include digit characters, and all characters that have the Unicode numeric value property such as Subscript (₁
, ₂
, ₃
, etc.), Superscript (¹
, ²
, ³
, etc.), Vulgar Fractions (⅕
, etc.).
Syntax
my_string.isnumeric()
isnumeric() Parameters
Python String isnumeric()
function does not take any parameters.
isnumeric() Return Value
Python String isnumeric()
function returns:
True
if ALL characters in the string are numeric characters.False
if AT LEAST ONE character is NOT numeric.
Examples
Example 1: Check if a String is numeric with isnumeric()
The isnumeric()
method returns True
if all characters in the string are numeric characters.
my_str = '123'
result = my_str.isnumeric()
print(result) # Output: True
output
True
The isnumeric()
method returns False
if at least one character is not numeric.
For example, string of a float point number is not numeric:
my_str = '123.456'
result = my_str.isnumeric()
print(result) # Output: False
output
False
For example, string of number with thousands separator is not numeric:
my_str = '1,234,567'
result = my_str.isnumeric()
print(result) # Output: False
output
False
For example, empty string is not numeric:
my_str = ''
result = my_str.isnumeric()
print(result) # Output: False
output
False
Example 2: Check if a String with Unicode Numeric Characters is decimal with isnumeric()
Unicode characters, like U+0660
(Arabic-Indic Digit Zero), Subscript digits(₁
, ₂
, ₃
, etc.), Superscript digits(¹
, ²
, ³
, etc.) and Vulgar Fractions (⅕
, etc.), are also considered as numeric characters.
my_str1 = '\u0660'
my_str2 = '\u00B23455' # my_str2 = '²3455'
my_str3 = '\u00BD' # my_str3 = '½'
print(my_str1.isnumeric()) # Output: True
print(my_str2.isnumeric()) # Output: True
print(my_str3.isnumeric()) # Output: True
output
True
True
True
isnumeric() method vs isdecimal() method vs isdigit() method
The main difference between the isnumeric()
, isdecimal()
and isdigit()
methods is that:
-
isnumeric()
method supports Digits, Vulgar Fractions, Subscripts, Superscripts, Roman Numerals, Currency Numerators. -
isdecimal()
method supports only Decimal Number -
isdigit()
method supports Decimals, Subscripts, Superscripts
Example with '123'
as String:
print('123'.isdecimal()) # Output True
print('123'.isdigit()) # Output True
print('123'.isnumeric()) # Output True
output
True
True
True
Example with Superscript Two '²'
(that is '\u00b2'
) as String:
print('\u00b2'.isdecimal()) # Output False
print('\u00b2'.isdigit()) # Output True
print('\u00b2'.isnumeric()) # Output True
output
False
True
True
Example with Vulgar Two '⅓'
(that is '\u2153'
) as String:
print('\u2153'.isdecimal()) # Output False
print('\u2153'.isdigit()) # Output False
print('\u2153'.isnumeric()) # Output True
output
False
False
True