Adding and Formatting Paragraphs
In the previous lesson, we learned how to add headings
and paragraphs
to a document.
The most fundamental element when writing a document, and the one most frequently used, is the Paragraph
.
Using python-docx, you can easily add large volumes of text content or programmatically apply conditional formatting.
Adding a Paragraph
To add a paragraph, you use the add_paragraph()
method.
You pass the text you want to add to the paragraph as an argument to add_paragraph.
doc.add_paragraph('This is the first paragraph.')
The code above adds a new paragraph to the document containing the text "This is the first paragraph."
Adding Multiple Paragraphs
By using the add_paragraph method along with a loop
, you can add multiple paragraphs at once.
texts = ['This is the first paragraph.', 'This is the second paragraph.', 'This is the third paragraph.']
for text in texts:
doc.add_paragraph(text)
This is the first paragraph.
This is the second paragraph.
This is the third paragraph.
You can use this approach to easily add large amounts of data from an Excel file or other sources to a document.
Formatting Text
By using the run
object, you can style text added to a paragraph in various ways.
This object is a part of the Paragraph
object and represents a portion of the text with specific formatting within the paragraph.
A run object represents a consecutive run of text with the same formatting, and you can use multiple runs to compose a single paragraph.
# Create a new document
doc = Document()
# Add a paragraph to the document
paragraph = doc.add_paragraph('This text is ')
run = paragraph.add_run('1. bold ')
run.bold = True # Set bold
run = paragraph.add_run('2. and ')
run.italic = True # Set italic
run = paragraph.add_run('3. large')
run.font.size = Pt(24) # Set font size
This code sets the following attributes to the text within a single paragraph using bold
, italic
, and font size 24pt
for the specified words.
Applying Styles to Paragraphs
You can apply styles like 'Title' and 'Subtitle' from Word to paragraphs as follows.
doc.add_paragraph('Document Title', style='Title')
doc.add_paragraph('Subtitle', style='Subtitle')
In this lesson, we learned how to add paragraphs and format the text within them.
In the next lesson, we will learn how to add lists to a document.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.