0

i have to search for certain patterns in a file that i have to open. If all the variables find the patterns, my code works fine, but if any pattern is not found, i receive the following error:

str2 = len(max(re.findall(r'(?:TTTTTTCT)+', data))) // 8
ValueError: max() arg is an empty sequence

what can i do to assign a default value to not receive this error in case one of the variables receive an empty sequence?

Sorry if i can't explain properly, english is not my native language and also i'm a beginner

these are my variables:

with open(sys.argv[2], "r") as myfile:
    data = myfile.read()

str1 = len(max(re.findall(r'(?:AGATC)+', data))) // 5

str2 = len(max(re.findall(r'(?:TTTTTTCT)+', data))) // 8

str3 = len(max(re.findall(r'(?:AATG)+', data))) // 4

str4 = len(max(re.findall(r'(?:TCTAG)+', data))) // 5

str5 = len(max(re.findall(r'(?:GATA)+', data))) // 4

str6 = len(max(re.findall(r'(?:TATC)+', data))) // 4

str7 = len(max(re.findall(r'(?:GAAA)+', data))) // 4

str8 = len(max(re.findall(r'(?:TCTG)+', data))) // 4
2
  • It's not entirely clear what you want your max call to be doing. Currently it will select the lexicographically maximal string matched by your regex but it's not clear that's actually what you want. If you want the longest string, you probably want to be calling len earlier, and you might be able to inject a zero more easily than you can with your current code. Commented Apr 12, 2020 at 18:44
  • @HeapOverflow actually str2 would be 2, but it's fine Commented Apr 12, 2020 at 20:45

1 Answer 1

1

You could use what is called a Try...Except block.

What this will do is first try the code you want, and if it errors, perform an action. You could do it on str1 for example, like so:

try:
    str1 = len(max(re.findall(r'(?:AGATC)+', data))) // 5
except:
    # This catches the specific error
    e = sys.exc_info()[0]

    # Set str1 to a default value
    str1 = "foo"

    # Print out the error for reference
    print("Received Error: {}".format(e))

Also see this reference.

You could repeat this for each of your str variables

Sign up to request clarification or add additional context in comments.

1 Comment

You almost never should use a bare except clause, some exceptions (like KeyboardInterupt generated by Ctrl+C, or SystemExit generated by calling sys.exit) should always be allowed to propagate. If you want to catch most exceptions (but not the ones I list above), catch the Exception type. That also lets you use as e to bind the exception object to a name, rather than needing to mess with sys.exec_info. And probably you only want to catch specific exceptions, like ValueError here.

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.