Heim  >  Artikel  >  Backend-Entwicklung  >  python判断字符串是否纯数字的方法

python判断字符串是否纯数字的方法

WBOY
WBOYOriginal
2016-06-06 11:20:201971Durchsuche

本文实例讲述了python判断字符串是否纯数字的方法。分享给大家供大家参考。具体如下:

判断的代码如下,通过异常判断不能区分前面带正负号的区别,正则表达式可以根据自己需要比较灵活的写,通过isdigit方法用来判断是否是纯数字,测试代码如下

代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
a = "1"
b = "1.2"
c = "a"
#通过抛出异常
def is_num_by_except(num):
    try:
        int(num)
        return True
    except ValueError:
#        print "%s ValueError" % num
        return False
print "通过抛出异常"
print "a", is_num_by_except(a)   
print "b", is_num_by_except(b)
print "c", is_num_by_except(c)
print "通过isdigit()"
print "a", a.isdigit()
print "b", b.isdigit()
print "c", c.isdigit()
print "通过正则表达式"
import re
print "a", re.match(r"d+$", a) and True or False
print "b", re.match(r"d+$", b) and True or False
print "c", re.match(r"d+$", c) and True or False


输出结果如下:

代码如下:

通过抛出异常
a True
b False
c False
通过isdigit()
a True
b False
c False
通过正则表达式
a True
b False
c False
--EOF--


判断一个字符串只包含数字字符

一种方法是 a.isdigit()。但这种方法对于包含正负号的数字字符串无效,因此更为准确的为:

代码如下:

try:
    x = int(aPossibleInt)
    … do something with x …
except ValueError:
    … do something else …


这样更准确一些,适用性也更广。但如果你已经确信没有正负号,使用字符串的isdigit()方法则更为方便。
还可以用正则表达式:

代码如下:

re.match(r'[+-]?d+$', '-1234′)


在数字很大时,可能比用int类型转换速度更快。

希望本文所述对大家的Python程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn