Python judges whether a string is a pure number

There are three ways for python to judge whether a string is a number: isdecimal(), isdigit(),isnumeric()

serial number method illustrate
1 string.isdecimal() Returns True if the string contains only numbers, full-width numbers
2 string.isdigit() Return True if the string contains only numbers, full-width numbers, ①②(1),\u00b2
3 string.isnumeric() If the string only contains numbers, return True, full-width numbers, Chinese characters

isdecimal() Demo

# 1. 纯数字
string1 = '123'
print(string1.isdecimal())
print(string1.isdigit())
print(string1.isnumeric())

# > True
# > True
# > True

isdigit() Demo

# 2. unicode字符
string2_1 = '1'
string2_2 = '①②'
string2_3 = "\u00b2"
print(string2_1.isdecimal(), string2_2.isdecimal(), string2_3.isdecimal())
print(string2_1.isdigit(),   string2_2.isdigit(),   string2_3.isdigit()  )
print(string2_1.isnumeric(), string2_2.isnumeric(), string2_3.isnumeric())

# > True False False
# > True True True
# > True True True

isnumeric() demo

# 3. 中文数字
string3_1 = "一千零一"
string3_2 = "壹贰叁"
print(string3_1.isdecimal(), string3_2.isdecimal())
print(string3_1.isdigit(),   string3_2.isdigit()  )
print(string3_1.isnumeric(), string3_2.isnumeric())

# > False False
# > False False
# > True True

Guess you like

Origin blog.csdn.net/annita2019/article/details/128891249