Jonathan Laliberte
Jonathan Laliberte

Reputation: 2725

Function that returns true or false if certain conditions are met?

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:

  1. has only eight characters.
  2. is a string type
  3. 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

Answers (3)

The6thSense
The6thSense

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

Rohit Jain
Rohit Jain

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

Darwin
Darwin

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

Related Questions