Python String isnumeric() Method
The isnumeric() method detects if the string consists of only numbers, which can be: Unicode numbers, full-angle numbers (double-byte), Roman numerals, Chinese numerals.
Exponents are similar to ² and fractions are similar to ½ also belong to numbers.
# s = '½'
s = '\u00BD'
Python String isnumeric() Syntax
isnumeric() method syntax.
str.isnumeric()
Python String isnumeric() Parameters
- None.
Python String isnumeric() Return Value
Returns True if the string contains only numeric characters, otherwise returns False
Python String isnumeric() Example#1
The following example shows an example of the isnumeric() method.
#!/usr/bin/python3
str1 = "apidemos2022"
print (str1.isnumeric())
str = "13567895432"
print (str1.isnumeric())
Output:
Python String isnumeric() Example#2
Unicode numbers.
#!/usr/bin/python3
#s = '²3455'
s = '\u00B23455'
print(s.isnumeric())
# s = '½'
s = '\u00BD'
print(s.isnumeric())
a = "\u0030" #unicode for 0
print(a.isnumeric())
b = "\u00B2" #unicode for ²
print(b.isnumeric())
c = "10km2"
print(c.isnumeric())
Output:
Python String isnumeric() Example#3
The difference between str.isdecimal()
and str.isdigit()
.
The str.isdecimal()
function returns True only for decimal numbers, while the function str.isdigit()
returns True for other unicode-supported characters.
Details can be output using the following code.
import itertools
line = '-' * 37
print(line)
print("| № | isdigit | isdecimal | chr")
print(line)
for number in itertools.chain(range(1000), range(4969, 4978), range(8304, 11000)):
char = chr(number)
if (char.isdigit() or char.isdecimal()):
print('| {0:>6} | {1:^7} | {2:^9} | {3:3} '.format(
number,
'+' if char.isdigit() else '-',
'+' if char.isdecimal() else '-',
char
)
)
Output: