python 判断字符串是否为数字
以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字:
实例(python 3.0+)
# -*- coding: utf-8 -*- # filename : test.py # author by : www.51frw.cn
def is_number(s): try: float(s) return true except valueerror: pass try: import unicodedata unicodedata.numeric(s) return true except (typeerror, valueerror): pass return false # 测试字符串和数字 print(is_number('foo')) # false print(is_number('1')) # true print(is_number('1.3')) # true print(is_number('-1.37')) # true print(is_number('1e3')) # true # 测试 unicode # 阿拉伯语 5 print(is_number('٥')) # true # 泰语 2 print(is_number('๒')) # true # 中文数字 print(is_number('四')) # true # 版权号 print(is_number('©')) # false
我们也可以使用内嵌 if 语句来实现:
执行以上代码输出结果为:
false true true true true true true true false更多方法
python isdigit() 方法检测字符串是否只由数字组成。
python isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!