vendredi 24 avril 2020

Python if statement and assignment

I am working with BeautifulSoup in Python to parse some XML. I find myself having to write code that looks like this

for document in soup.find_all('document'):
    if document.find('doc-number'):
        doc_number = document.find('doc-number').string
    # More similar if statements further down

I find writing the document.find('doc-number') twice: once in the if statement and once within the if block rather cumbersome and leading to long lines of code.

Is there a way I can make the code shorter and more Pythonic ?

Aucun commentaire:

Enregistrer un commentaire