Python 判断字符串是否为数字

1、原文地址:http://www.runoob.com/python3/python3-check-is-number.html

以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字:
# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

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('٥'))  # False
# 泰语 2
print(is_number(''))  # False
# 中文数字
print(is_number('')) # False
# 版权号
print(is_number('©'))  # False
我们也可以使用内嵌 if 语句来实现:
执行以上代码输出结果为:
False
True
True
True
True
False
False
False
False

2、原文地址:http://bbs.csdn.net/topics/370089561

#!/usr/bin/python
# -*- coding:utf-8 -*-
#
# http://blog.ithomer.net

import sys
import math

# 判断是否为数字
def isNum(value):
    try:
        value + 1
    except TypeError:
        return False
    else:
        return True

# 判断是否为数字
def isNum2(value):
    try:
        x = int(value)
    except TypeError:
        return False
    except ValueError:
        return False
    except Exception, e:
        return False
    else:
        return True


def test1():
    
    a = "123abcDE"
    print a.isalnum()       # True, 所有字符都是数字或者字母

    a = "abcDE"
    print a.isalpha()       # True, 所有字符都是字母

    a = "123.3"
    print a.isdigit()       # False, 所有字符都是数字

    a = "abcde"
    print a.islower()       # True, 所有字符都是小写

    a = "ABCDE"
    print a.isupper()       # True, 所有字符都是大写

    a = "Abcde"
    print a.istitle()       # True, 所有单词都是首字母大写,像标题

    a = "\t"
    print a.isspace()       # True, 所有字符都是空白字符、\t、\n、\r

    arr = (1, 2.1, -3, -4.5, '123a', 'abc', 'aBC', 'Abc', 'ABC', '\t')
    for a in arr:
        print a,isNum(a)

    '''
    1 True
    2.1 True
    -3 True
    -4.5 True
    123a False
    abc False
    aBC False
    Abc False
    ABC False
        False
    '''

    for a in arr:
        print a,isNum2(a)
    '''
    1 True
    2.1 True
    -3 True
    -4.5 True
    123a False
    abc False
    aBC False
    Abc False
    ABC False
        False
    '''

 

posted on 2016-10-14 17:04  ZhYQ_note  阅读(543)  评论(0)    收藏  举报

导航