Home > Blockchain >  How keep a loop result into a variable or list?
How keep a loop result into a variable or list?

Time:09-27

I have a question about how to keep a loop result into a variable or list?

import docx

doc = docx.Document("demo.docx")

text = []

def Text():
    
    for para in all_paras:
        if para.style.name == 'Normal (Web)':
            print("<p>"  
                  para.text   '</p>')
            

        if para.style.name == 'Heading 1':
            doc_title = para.text
            print('<h1>'  
                  doc_title  '</h1>')
            

        if para.style.name == 'Heading 2':
            doc_title = para.text
            print('<h2>'  
              doc_title   '</h2>')

        if para.style.name == 'Heading 3':
            doc_title = para.text
            print('<h3>'  
              doc_title   '</h3>')

        if para.style.name == 'Heading 4':
            doc_title = para.text
            print('<h4>'  
              doc_title   '</h4>')

        if para.style.name == None:
            print("nao encontrado")
                   
if __name__ == "__main__":
    Text()

The output below is correct, but I would like store all content into a variable. How can I do it?

Result:

< p>Ut sed nisl eget mi consectetur commodo. Ut vehicula ligula ac nibh sollicitudin tempus. Integer dictum non enim vulputate euismod. Phasellus maximus fermentum nibh nec pellentesque. Suspendisse pretium vel quam nec tristique. Praesent gravida tellus a tortor dapibus imperdiet. Sed viverra nunc in congue vulputate. In in ipsum pharetra, auctor tellus a, posuere ipsum. Vestibulum eget tincidunt arcu, lobortis varius eros. Morbi vestibulum efficitur commodo.</ p>

CodePudding user response:

You can do text.append instead of print

Ex: Change print("your string") to text.append("your string")

Then finally to make the text variable which is of type array to string, you can simply do textString = '\n'.join(text) after all the text.append statements if you want to use this as a string anywhere.

CodePudding user response:

change all print()s in your code to text.append()

  • Related