vendredi 7 août 2015

In python should I use try or If and why?

First of all, I know the difference between if and try and I am perfectly aware that their purposes are completely different -while one makes tests, the other manages errors. However, in this particular case, is it better to use if or try ?

#option1
def getListRank(self):
    for point in self.soup.findAll('td',class_="rank-cell"):
        p = (point.get_text().replace('\t','').replace('\n','')
                             .replace('\r','').replace(',',''))
        if 'T' in p:
            self.listRk.append(int(p.replace('T',''))
        else:
            self.listRk.append(int(p))
    return self.listRk 

I am very tempted to use the following option2, given the fact that I know that the only reason that could prevent from turning p into an integer is the presence of that 'T'. Therefore, would it be unusual or less efficient to write this :

#option2
def getListRank(self):
    for point in self.soup.findAll('td',class_="rank-cell"):
        p = (point.get_text().replace('\t','').replace('\n','')
                             .replace('\r','').replace(',',''))
        try:
            self.listRk.append(int(p))
        except:
            self.listRk.append(int(p.replace('T',''))                
    return self.listRk

I ask the questions because I read this before so I assume that it is "pythonic". However if there is a piece of explanation/convention I am more than interested.

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire