[英]How do you check in python whether a string contains only numbers?
如何檢查字符串是否只包含數字?
我在這里試了一下。 我想看看實現這一目標的最簡單方法。
import string
def main():
isbn = input("Enter your 10 digit ISBN number: ")
if len(isbn) == 10 and string.digits == True:
print ("Works")
else:
print("Error, 10 digit number was not inputted and/or letters were inputted.")
main()
if __name__ == "__main__":
main()
input("Press enter to exit: ")
您需要在str
對象上使用isdigit
方法:
if len(isbn) == 10 and isbn.isdigit():
str.isdigit()
如果字符串中的所有字符都是數字並且至少有一個字符,則返回 True,否則返回 False。 數字包括十進制字符和需要特殊處理的數字,例如兼容性上標數字。 這涵蓋了不能用於以 10 為基數形成數字的數字,例如 Kharosthi 數字。 形式上,數字是具有屬性值 Numeric_Type=Digit 或 Numeric_Type=Decimal 的字符。
使用str.isdigit
:
>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>
使用字符串isdigit函數:
>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False
您也可以使用正則表達式,
import re
例如:-1) word = "3487954"
re.match('^[0-9]*$',word)
例如:-2) word = "3487.954"
re.match('^[0-9\.]*$',word)
例如:-3) word = "3487.954 328"
re.match('^[0-9\.\ ]*$',word)
如您所見,所有 3 eg 意味着您的字符串中只有 no 。 因此,您可以按照他們提供的相應解決方案進行操作。
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
浮點數、負數等呢?之前的所有例子都是錯誤的。
直到現在我得到了這樣的東西,但我認為它可能會好很多:
'95.95'.replace('.','',1).isdigit()
僅當有一個或沒有 '.' 時才會返回 true。 在數字串中。
'9.5.9.5'.replace('.','',1).isdigit()
將返回 false
因為每次我遇到檢查問題是因為 str 有時可以是 None,如果 str 可以是 None,只使用 str.isdigit() 是不夠的,因為你會得到一個錯誤
AttributeError:“NoneType”對象沒有屬性“isdigit”
然后您需要首先驗證 str 是否為 None 。 為了避免多重 if 分支,一個明確的方法是:
if str and str.isdigit():
希望這對像我一樣有同樣問題的人有所幫助。
您可以在此處使用 try catch 塊:
s="1234"
try:
num=int(s)
print "S contains only digits"
except:
print "S doesn't contain digits ONLY"
我可以想到兩種方法來檢查字符串是否所有數字都不是
方法1(使用python內置的isdigit()函數):-
>>>st = '12345'
>>>st.isdigit()
True
>>>st = '1abcd'
>>>st.isdigit()
False
方法2(在字符串之上執行異常處理):-
st="1abcd"
try:
number=int(st)
print("String has all digits in it")
except:
print("String does not have all digits in it")
上述代碼的輸出將是:
String does not have all digits in it
您可以使用 str.isdigit() 方法或 str.isnumeric() 方法
你也可以使用這個:
re.match(f'^[\d]*$' , YourString)
解決方案:
def main():
isbn = input("Enter your 10 digit ISBN number: ")
try:
int(isbn)
is_digit = True
except ValueError:
is_digit = False
if len(isbn) == 10 and is_digit:
print ("Works")
else:
print("Error, 10 digit number was not inputted and/or letters were inputted.")
main()
if __name__ == "__main__":
main()
input("Press enter to exit: ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.