Below input file has:
info:pens-10-books-10,pens-10-books-20
I am reading this input file using python dictionary like below.
d = {}
with open('inputfile.txt') as f:
for line in f:
if ":" not in line:
continue
key, value = line.strip().split(":", 1)
d[key] = value
for key, value in d.iteritems():
if key == 'info':
goods = value.split(",")
Now I need help here to validate the input provided that is. goods declared as list so i need validate list values.
first octet must be alphabet, second octet must be number, third octet must be alphabet, fourth octet must be number. if contains more than 4 octets not valid input . Below are the examples
pens-10-books-10 --input valid
apples-1-cakes-10 --input valid
10-aplpes-10cakes --not valid input (as number contains at first octet)
pens-10-books-20-apples-10 -- not valid input (more than 4 octets)
You can use a regex which validates that your input matches your pattern:
>>> import re
>>>
>>> def validate(string):
if re.match(r'^[a-zA-Z]+\-\d+\-[a-zA-Z]+\-\d+$', string):
return True
return False
>>> validate('pens-10-books-10')
True
>>> validate('apples-1-cakes-10')
True
>>> validate('10-aplpes-10cakes')
False
>>> validate('pens-10-books-20-apples-10')
False
>>>
To use this with your goods
list, you can iterate over each element testing and displaying if it is valid:
>>> goods = ['pens-10-books-10', 'apples-1-cakes-10',
'10-aplpes-10cakes', 'pens-10-books-20-apples-10']
>>>
>>> for string in goods:
print(validate(string))
True
True
False
False
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.