# 案例十:判断字符串是否为数字 # 定义一个自定义函数 is_number() 方法来判断字符串是否为数字 def is_number(s): try: float(s) # 若不能给定的字符串不能转换为数字,则会出现ValueError return True except ValueError: pass try: import unicodedata # unicodedata模块部分 unicodedata.numeric(s) # 把一个表示数字的字符转换为浮点数。比如,可将‘5’、'五’转换数值输出 return True except(TypeError,ValueError): # 上述出现了转换不了的情况,会出现类型错误(TypeError) pass return False print(is_number("五")) # True print(is_number(5)) # True print(is_number("5")) # True print(is_number("a")) # False
PYTHON100个案例训练——10
最新推荐文章于 2024-08-14 17:18:35 发布
文章定义了一个is_number()函数,通过尝试将字符串转换为浮点数或利用unicodedata.numeric方法来判断字符串是否表示数字。对于无法转换的字符串,函数返回False。示例展示了该函数能正确识别中文数字和阿拉伯数字。
摘要由CSDN通过智能技术生成