Python String isnumeric() function returns True
if all the characters in the string are numeric, otherwise False
. If the string is empty, then this function returns False
.
Python String isnumeric()
Numeric characters include digit characters, and all characters that have the Unicode numeric value property. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
Let’s look at some examples of Python string isnumeric() function.
s = '2019'
print(s.isnumeric())
Output: True
because all the characters in the string are numerical.
s = 'Hello 2019'
print(s.isnumeric())
Output: False
because some of the characters in the string are not numerical.
s = ''
print(s.isnumeric())
Output: False
because it’s an empty string.
Let’s look into some examples with special Unicode characters that are numerical.
s = '¼' # 00bc: ¼ (VULGAR FRACTION ONE QUARTER)
print(s)
print(s.isnumeric())
s = '⒈⒗' #2488: ⒈ (DIGIT ONE FULL STOP), 2497: ⒗ (NUMBER SIXTEEN FULL STOP)
print(s)
print(s.isnumeric())
Output:
¼
True
⒈⒗
True
Print all Unicode Numeric Characters
We can use unicodedata
module to print all the unicode characters that are considered as numeric.
import unicodedata
count = 0
for codepoint in range(2 ** 16):
ch = chr(codepoint)
if ch.isnumeric():
print(u'{:04x}: {} ({})'.format(codepoint, ch, unicodedata.name(ch, 'UNNAMED')))
count = count + 1
print(f'Total Number of Numeric Unicode Characters = {count}')
Output:
0030: 0 (DIGIT ZERO)
0031: 1 (DIGIT ONE)
...
ff16: 6 (FULLWIDTH DIGIT SIX)
ff17: 7 (FULLWIDTH DIGIT SEVEN)
ff18: 8 (FULLWIDTH DIGIT EIGHT)
ff19: 9 (FULLWIDTH DIGIT NINE)
Total Number of Numeric Unicode Characters = 800
I never thought that there will be 800 Unicode characters that are numeric. 🙂
Reference: Official Documentation