0

I am new to Python, and am confused by the literature as to how to design a function to display error messages when the input is either not a string of length 21. This is the latest permutation that is not working. For a string of length 19 for example, it does not return the right error message. My background is not in comp sci, so any help on this and an explanation as to how this works would be helpful. Thanks

test = "test_string_for_slice"
test2 = "test_string_for_"

def stringSlice(x):
    if type(x) != str:
        raise Exception("The input is not a string.")
    elif len(x) != 21:
        raise ValueError("The input is not exactly 21 characters.")
    else:
        slice1 = x[0:6]
        slice2 = x[6:12]
        slice3 = x[13:]
        return slice1, slice2, slice3

stringSlice(test)
stringSlice(test2) #this should return an error but does not
7
  • 1
    What is occCode? Commented Nov 20, 2017 at 21:41
  • 1
    change occCode to x which is the parameter the function is provided with. Commented Nov 20, 2017 at 21:43
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Commented Nov 20, 2017 at 21:46
  • yes change occCode to x. sorry about that Commented Nov 20, 2017 at 21:51
  • 1
    It appears your code is working as it is supposed to? Commented Nov 20, 2017 at 21:55

1 Answer 1

1

It seems you're using a variable occCode when you mean to use x.

def stringSlice(x):
    if type(x) != str:
        raise Exception("The input is not a string.")
    elif len(x) != 21:   #Note this is where things got changed!!!
        raise ValueError("The input is not exactly 21 characters.")
    else:
        slice1 = x[0:6]
        slice2 = x[6:12]
        slice3 = x[13:]
        return slice1, slice2, slice3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.