Python字符串isnumeric()

时间:2020-02-23 14:43:27  来源:igfitidea点击:

如果字符串中的所有字符均为数字,则Python String isnumeric()函数将返回True,否则返回False。
如果字符串为空,则此函数返回False。

Python字符串isnumeric()

数字字符包括数字字符,以及所有具有Unicode数字值属性的字符。
形式上,数字字符是具有属性值Numeric_Type =数字,Numeric_Type =十进制或者Numeric_Type =数字的字符。

我们来看一些Python字符串isnumeric()函数的示例。

s = '2019'

print(s.isnumeric())

输出:True,因为字符串中的所有字符都是数字。

s = 'Hello 2019'
print(s.isnumeric())

输出:False,因为字符串中的某些字符不是数字。

s = ''
print(s.isnumeric())

输出:False,因为它是一个空字符串。

我们来看一些带有特殊Unicode数字字符的示例。

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())

输出:

¼
True
⒈⒗
True

打印所有Unicode数字字符

我们可以使用unicodedata模块来打印所有被认为是数字的unicode字符。

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}')

输出:

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