Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/except to check string

Tags:

python

I am confused on how to use Try/Exception and if/else. How can I write idiomatic code if I want to tell the user to provide .html file

if url[-4:] ==".html":
        // do your things
else: 
    print('Error! the file is not html file')

I am checking whether I should use try/exception in such scenarios or if/else as I did.

like image 809
user3378649 Avatar asked May 13 '26 17:05

user3378649


2 Answers

In a nutshell:

try:
    a = q.get()

try means try this thing, if it works, use it, else except something else if it fails, or it works, and there is an error such as ValueError.

except:
    a = None

Updated:

try:
   url[-4:] == ".html"

except: 
    print "Error"
like image 188
Jonathan Davies Avatar answered May 15 '26 07:05

Jonathan Davies


In Python, it's Easier to ask for forgiveness than permission. In other words, the idiomatic way in Python would be to just let the exception be thrown and react accordingly, instead of explicitly checking the condition ("Look before you leap", also in the linked glossary). So your code should look like this:

try:
    # do your thing with `url`
except:
    print('Error! the file is not html file')
like image 41
Óscar López Avatar answered May 15 '26 06:05

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!