1

try:
    pos = name.find("#")
    name = name[:pos]
except:
    pass
try:
    pos = name.find("TDCJ")
    name = name[:pos]
except:
    pass

Is there a way to combine these two try and except? My program keeps on building I feel like there is way too many try and excpet blocks. How do I avoid adding try and except often?

1
  • 1
    Depending on your actual code, this might be a case of DRY, so maybe think about putting that into a function. Also keep in mind, that the except should actually have action to handle the problem. I guess/hope the pass there is just for a more concise question here. Commented Jul 29, 2020 at 8:33

1 Answer 1

1

If the try-except is the same you can just loop the desired string elements. Something like the following:

l = ["#", "TDCJ"]

for elem in l:
    try:
        pos = name.find(elem)
        name = name[:pos]
    except:
        pass

Generally, you should keep the Dont Repeat Yourself (DRY) principle

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.