Reputation: 2725
So a user will input a string value in binary format. i.e. '01000001'
I want to check the value they enter to see if it:
- has only eight characters.
- is a string type
- and only contains '0's or '1's
preferably to be done with a function that takes in the user value so that i can call it whenever. Returns false if conditions are not met.
this is what i came up with so far...
size = len(teststring)
teststring = '11111111'
def typecheck(value):
if type(user_input) == type(teststring) and len(user_input) == size and contains only 1 | 0
return
Upvotes: 1
Views: 3229
Reputation: 8335
No need for regex
You could use str.strip()
and strip all 1
and 0
from end and beginning and check.
Code:
check = "11101110"
if isinstance(check,str) and len(check)==8 and check.strip("01")=='':
print "yes"
Output:
yes
Upvotes: 4
Reputation: 213321
You can use regex matching here:
reg = re.compile(r'^[01]{8}$')
def typecheck(value):
return isinstance(value, str) and bool(reg.match(value))
Or since you want to check for binary format number, how about converting it to int
with base 2, and see if it's a valid conversion:
def typecheck(value):
try:
return len(value) == 8 and bool(int(value, 2))
except TypeError, ValueError:
return False
Upvotes: 8
Reputation: 519
This can be done with one if
statement. If the regex doesn't find a match it will return None
which evaluates to False
in a truth test.
import re
def check_input(user_input):
if not re.match(r'^[01]{8}$', user_input):
it doesn't meet requirements do something
Upvotes: 1