python判斷字串是否純數字代碼

來源:互聯網
上載者:User

判斷的代碼如下,通過異常判斷不能區分前面帶加號或減號的區別,Regex可以根據自己需要比較靈活的寫,通過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 "通過Regex"
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
通過Regex
a True
b False
c False
--EOF--

判斷一個字串只包含數字字元

A:一種方法是 a.isdigit()。但這種方法對於包含加號或減號的數字字串無效,因此更為準確的為:

 代碼如下 複製代碼

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

這樣更準確一些,適用性也更廣。但如果你已經確信沒有加號或減號,使用字串的isdigit()方法則更為方便。

還可以用Regex:

 代碼如下 複製代碼

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

在數字很大時,可能比用int類型轉換速度更快。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.