7.2 小注: str函数isdigit、isdecimal、isnumeric的区别修正
str函数isdigit、isdecimal、isnumeric的区别
isdigit()
True: Unicode数字,全角数字(双字节),byte数字(单字节)
False: 汉字数字,罗马数字
Error: 无
经测试,在Python2.7.18与python3.8.2中罗马数字.isdigit()为False;
上处为学习时所发现的错误;
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)
isdecimal()
True: Unicode数字,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)
示例:
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Author: Fan Carey
# Version 1.0
# Created time:2020.05.07
# Description: 测试str函数isdigit、isdecimal、isnumeric的区别
# unicode
num_1 = "4"
print("unicode.isdigit", num_1.isdigit())
# 输出:unicode.isdigit True
print("unicode.isnumeric", num_1.isnumeric())
# 输出:unicode.isnumeric True
print("unicode.isdecimal", num_1.isdecimal())
# 输出:unicode.isdecimal True
# Full-width
num_2 = "4"
print("Full-width.isdigit", num_2.isdigit())
# 输出:Full-width.isdigit True
print("Full-width.isnumeric", num_2.isnumeric())
# 输出:Full-width.isnumeric True
print("Full-width.isdecimal", num_2.isdecimal())
# 输出:Full-width.isdecimal True
# byte
num_3 = b"4"
print("byte.isdigit:", num_3.isdigit())
# 输出:byte.isdigit: True
print(num_3.isnumeric())
# 输出:AttributeError: 'bytes' object has no attribute 'isnumeric'
print(num_3.isdecimal())
# AttributeError: 'bytes' object has no attribute 'isdecimal'
# 罗马数字
num_4 = "Ⅳ"
print("罗马数字.isdigit", num_4.isdigit())
# 输出:罗马数字.isdigit False
print("罗马数字.isnumeric", num_4.isnumeric())
# 输出:罗马数字.isnumeric True
print("罗马数字.isdecimal", num_4.isdecimal())
# 输出:罗马数字.isdecimal False
# 汉字
num_5 = "四"
print("汉字.isdigit", num_5.isdigit())
# 输出:汉字.isdigit False
print("汉字.isnumeric", num_5.isnumeric())
# 输出:汉字.isnumeric True
print("汉字.isdecimal", num_5.isdecimal())
# 输出:汉字.isdecimal False