我正在讀取 csv 檔案,我需要檢查其中一個欄位是否具有正確的內容。它需要由數字 (0-9) 和可能的“-”組成。例如:
“12345”正確
“12345-1”正確
“12345a”錯誤
我嘗試使用int(),但它只適用于數字,破折號也是可以接受的。
謝謝你的幫助。
uj5u.com熱心網友回復:
您可以在驗證前str.isnumeric結合使用str.replace來去除破折號:
s = "12345-1"
is_valid = s.replace('-', '').isnumeric() # True
uj5u.com熱心網友回復:
從這個答案中得出的邏輯更普遍適用。要測驗字串,請運行它,它可以適用于整個 csv。
import re
word = '12345a'
special_char = False
regexp = re.compile('[^0-9-]')
if regexp.search(word):
special_char = True
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365257.html
