I am reading a csv a file and I need to check if one of the fields has the correct content. It needs to be compound by numbers (0-9) and possible "-". For example:
"12345" Corrrect
"12345-1" Corrrect
"12345a" Incorrrect
I tried using int()
, but it only works for numbers, Dashes are acceptable as well.
Thank you for all your help.
CodePudding user response:
You can use str.isnumeric
combined with str.replace
to strip the dashes before validation:
s = "12345-1"
is_valid = s.replace('-', '').isnumeric() # True
CodePudding user response:
Logic taken from this answer which applies more generally. To test a string run this, which can be adapted to work for the whole csv.
import re
word = '12345a'
special_char = False
regexp = re.compile('[^0-9-]')
if regexp.search(word):
special_char = True