<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Vikram Aruchamy - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Vikram Aruchamy - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 19 May 2026 22:44:33 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/askvikram/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Write Math Equations in Google Docs ]]>
                </title>
                <description>
                    <![CDATA[ Math equations are a critical part of academic papers, research reports, and technical documentation. While LaTeX is widely used for professional typesetting, Google Docs offers a robust set of features for inserting and formatting math equations and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/write-math-equations-in-google-docs/</link>
                <guid isPermaLink="false">68275cf15ed8a1db0cf8769b</guid>
                
                    <category>
                        <![CDATA[ Google Docs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Mathematics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ chatgpt ]]>
                    </category>
                
                    <category>
                        <![CDATA[ chatgptguide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Fri, 16 May 2025 15:42:41 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747410133881/93c8cf6e-6cbb-4890-8023-fcc2fdaa0fa2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Math equations are a critical part of academic papers, research reports, and technical documentation. While LaTeX is widely used for professional typesetting, Google Docs offers a robust set of features for inserting and formatting math equations and also supports LaTeX-style input.</p>
<p>Whether you're a student submitting a math assignment or a professional documenting formulas, Google Docs provides multiple ways to insert and format equations efficiently.</p>
<p>In this article, you'll learn how to <a target="_blank" href="https://support.google.com/docs/answer/160749">write math equations in Google Docs</a> using different methods, including using Google Docs’ built-in equation editor and typing LaTeX-style commands directly, inserting complex equations with the help of the Auto-LaTeX add-on, and copying math equations from <a target="_blank" href="https://chromewebstore.google.com/detail/chatgpt-to-google-docs-or/oibghjgooccojibfacdonaoipegckdeg">ChatGPT to Google Docs</a> without losing formatting by using the ChatGPT to Google Docs or PDF Chrome extension.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-write-equations-using-the-built-in-equation-editor">How to Write Equations Using the Built-in Equation Editor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-write-equations-using-latex-commands">How to Write Equations Using LaTeX Commands</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-auto-latex-add-on-for-writing-advanced-math-equations">How to Use Auto Latex Add-on for Writing Advanced Math Equations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-copy-math-equations-from-chatgpt-to-google-docs">How to Copy Math Equations from ChatGPT to Google Docs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-watch-how-to-write-equations-in-google-docs">Watch: How to Write Equations in Google Docs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tips-for-formatting-math-equations-in-google-docs">Tips for Formatting Math Equations in Google Docs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-how-to-write-equations-using-the-built-in-equation-editor"><strong>How to Write Equations Using the Built-in Equation Editor</strong></h2>
<p>Google Docs has a built-in equation editor that makes it easy to insert mathematical symbols and expressions.</p>
<p>To insert an equation editor box:</p>
<ol>
<li><p>Open your Google Docs document.</p>
</li>
<li><p>Go to the top menu and click <em>Insert</em> → <em>Equation</em>.</p>
</li>
<li><p>An equation editor will appear, and a new toolbar will show up with common math symbols like fractions, exponents, Greek letters, and more.</p>
</li>
</ol>
<p>Alternatively, you can use the following keyboard shortcuts to insert an equation editor box. </p>
<ul>
<li><p><strong>Windows/Linux:</strong> <code>Alt</code> + <code>I</code>, then <code>E</code></p>
</li>
<li><p><strong>Mac:</strong> <code>Control</code> + <code>Option</code> + <code>I</code>, then <code>E</code></p>
</li>
</ul>
<p>This shortcut quickly opens the equation editor without clicking through menus.</p>
<p><strong>Toolbar Symbols:</strong></p>
<p>Once the toolbar appears, you’ll find buttons for:</p>
<ul>
<li><p>Greek letters</p>
</li>
<li><p>Miscellaneous operations</p>
</li>
<li><p>Relations</p>
</li>
<li><p>Math operations</p>
</li>
<li><p>Arrows</p>
</li>
</ul>
<p>The equation editor box and a toolbar look like the following:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747198733591/9defa152-16a5-42a1-b098-228a9d1f7f79.png" alt="Google Docs Equation Editor and Toolbar" class="image--center mx-auto" width="1340" height="450" loading="lazy"></p>
<p>Now let’s learn how to write equations using the equation editor with a practical example.</p>
<h3 id="heading-example-typing-the-quadratic-formula">Example: Typing the Quadratic Formula</h3>
<p>Follow these steps to insert the following quadratic formula in Google Docs:</p>
<p>$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$</p><ol>
<li><p>Go to <em>Insert</em> → <em>Equation</em> to insert an equation editor and enable the equation toolbar.</p>
</li>
<li><p>Type <code>x=</code></p>
</li>
<li><p>Click the Math Operations dropdown (the one with templates like square roots, brackets), then select the fraction template. This inserts a placeholder with two parts: a numerator and a denominator.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747199319708/142157c9-f997-494a-be4a-efb619b7c12d.png" alt="Screenshot of Google Docs displaying a feature to insert math equations. A dropdown menu shows various mathematical symbols like fractions, square roots, and integrals. " class="image--center mx-auto" width="721" height="418" loading="lazy"></p>
</li>
<li><p>Click inside the numerator field. Begin by typing <code>-b</code>.</p>
</li>
<li><p>Now insert the ± (plus-minus) symbol. To do this:</p>
<ul>
<li><p>Click the Miscellaneous Operations dropdown</p>
</li>
<li><p>Select the ± symbol from the list.<br>  Your numerator should now show: <code>-b ±</code> as in the following image:</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747199567908/be5daee7-2ed2-4c86-be16-d90e033a05be.png" alt="Screenshot of Google Docs showing a math equation being edited with the equation toolbar open. Various symbols are visible on the toolbar, and part of a quadratic formula is visible in the document area." class="image--center mx-auto" width="766" height="362" loading="lazy"></p>
</li>
</ul>
</li>
<li><p>After the ± symbol, insert a square root:</p>
<ul>
<li><p>Go back to the Math Operations dropdown and select the square root template.</p>
</li>
<li><p>Inside the root, type <code>b^2 - 4ac</code>.</p>
<ul>
<li><p>Use <code>^</code> to enter exponents. For example, <code>b^2</code> will be rendered as <em>b²</em>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747199681755/cc2084c2-5856-4999-9905-d825b5c276d9.png" alt="Screenshot of Google Docs showing a math equation being inserted. A dropdown menu displays mathematical symbols like fractions, square roots, and integrals. A formula for the quadratic equation is in the document area on the right." class="image--center mx-auto" width="775" height="393" loading="lazy"></p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>Move to the denominator field and type <code>2a</code>.</p>
</li>
</ol>
<p>Now your full equation should appear as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747199739733/2c1ef4f8-9730-491f-9120-5ba6daee41c3.png" alt="Screenshot of Google Docs showing an open document. It has menu options at the top and a formula for the quadratic equation displayed on the page." class="image--center mx-auto" width="805" height="352" loading="lazy"></p>
<p>The equation will be properly formatted using Google Docs’ equation rendering, making it easy to read and mathematically accurate. You can continue typing more text below or beside the equation as needed – it behaves like any other element in your document.</p>
<p>This approach is useful for inserting neatly formatted equations without relying on add-ons or external tools. It’s especially helpful for students, teachers, and professionals preparing technical documents directly in Google Docs.</p>
<h2 id="heading-how-to-write-equations-using-latex-commands">How to Write Equations Using LaTeX Commands</h2>
<p>If you're familiar with <a target="_blank" href="https://www.latex-project.org/"><strong>LaTeX</strong></a>, you can take advantage of Google Docs’ support for a subset of LaTeX-style commands inside the built-in equation editor. This can greatly speed up the process of entering complex mathematical expressions, especially if you're already comfortable with LaTeX syntax.</p>
<h3 id="heading-how-to-use-latex-commands-in-google-docs">How to Use LaTeX Commands in Google Docs</h3>
<ol>
<li><p>Open your Google Docs document.</p>
</li>
<li><p>Go to Insert → Equation to activate the equation toolbar and equation input field.</p>
</li>
<li><p>Click inside the equation box. Instead of using the toolbar buttons, type LaTeX-style commands directly.</p>
</li>
<li><p>As you type, Google Docs will automatically render the commands into formatted math once you press space or enter after each command or expression.</p>
</li>
</ol>
<h4 id="heading-commonly-supported-latex-commands-in-google-docs">Commonly Supported LaTeX Commands in Google Docs:</h4>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Instruction</strong></td><td><strong>Result</strong></td></tr>
</thead>
<tbody>
<tr>
<td>To insert a fraction</td><td><code>\frac{a}{b}</code> → 𝑎⁄𝑏</td></tr>
<tr>
<td>To insert a square root</td><td><code>\sqrt{x}</code> → √𝑥</td></tr>
<tr>
<td>To insert Greek letters like α, β</td><td><code>\alpha, \beta</code> → α, β</td></tr>
<tr>
<td>To insert an integral with limits</td><td><code>\int_a^b f(x)\,dx</code> → ∫ᵃᵇ 𝑓(𝑥) 𝑑𝑥</td></tr>
<tr>
<td>To insert x superscript 2</td><td><code>x^2</code> → 𝑥²</td></tr>
<tr>
<td>To insert x subscript 1</td><td><code>x_1</code> → 𝑥₁</td></tr>
</tbody>
</table>
</div><p>Type these commands in the equation box, and when you press space or enter, they will be converted to properly formatted mathematical notation.</p>
<h4 id="heading-example-typing-the-quadratic-formula-using-latex-commands">Example: Typing the Quadratic Formula Using LaTeX Commands</h4>
<p>Let’s walk through how to enter the following quadratic formula using LaTeX-style commands:</p>
<p>$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$</p><p><strong>Steps:</strong></p>
<ol>
<li><p>Insert the equation box: Go to Insert → Equation.</p>
</li>
<li><p>In the equation input area, type the following:</p>
</li>
</ol>
<pre><code class="lang-javascript">x = \frac{-b \pm \sqrt{b^<span class="hljs-number">2</span> - <span class="hljs-number">4</span>ac}}{<span class="hljs-number">2</span>a}
</code></pre>
<ul>
<li><p><code>\frac</code> creates a fraction.</p>
</li>
<li><p><code>-b</code> is the numerator’s first term.</p>
</li>
<li><p><code>\pm</code> inserts the plus-minus symbol.</p>
</li>
<li><p><code>\sqrt</code> creates a square root.</p>
</li>
<li><p><code>b^2</code> formats <em>b squared</em>.</p>
</li>
<li><p><code>- 4ac</code> is written normally inside the square root.</p>
</li>
<li><p><code>2a</code> is the denominator.</p>
</li>
</ul>
<ol start="3">
<li>As you type, press space or enter after each LaTeX command. Google Docs will automatically convert the code into properly formatted math notation.</li>
</ol>
<p>After rendering, the equation will appear as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747199739733/2c1ef4f8-9730-491f-9120-5ba6daee41c3.png" alt="A Google Docs interface showing the quadratic formula being entered as a math equation" width="805" height="352" loading="lazy"></p>
<p>This method is ideal for users who prefer keyboard-based input over clicking toolbar icons. It also allows you to enter complex expressions faster and more accurately, especially if you're familiar with standard LaTeX syntax.</p>
<h4 id="heading-notes">Notes:</h4>
<ul>
<li><p>Not all LaTeX features are supported in Google Docs. The supported commands are limited to basic math formatting, Greek letters, and common symbols.</p>
</li>
<li><p>Make sure to press <strong>space</strong> after each LaTeX command so that Docs knows to render it.</p>
</li>
</ul>
<h2 id="heading-how-to-use-auto-latex-add-on-for-writing-advanced-math-equations">How to Use Auto Latex Add-on for Writing Advanced Math Equations</h2>
<p>When generating mathematical content using tools like ChatGPT, you'll notice that equations are <strong>rendered visually on the webpage</strong>, but behind the scenes they’re created using <a target="_blank" href="https://www.latex-project.org/">LaTeX</a> code. So when you copy content from ChatGPT into Google Docs, the equations come through as raw LaTeX code rather than rendered math expressions.</p>
<p>For example, a quadratic formula provided by ChatGPT might look like this when pasted into your document:</p>
<pre><code class="lang-javascript">x = \frac{-b \pm \sqrt{b^<span class="hljs-number">2</span> - <span class="hljs-number">4</span>ac}}{<span class="hljs-number">2</span>a}
</code></pre>
<p>While this format is ideal for precision, Google Docs doesn’t support LaTeX rendering by default.</p>
<p>This is where the <strong>Auto-LaTeX Equations</strong> add-on becomes essential, especially if you're moving content from <a target="_blank" href="https://www.docstomarkdown.pro/chatgpt-to-google-docs/">ChatGPT to Google Docs</a>. It’s also incredibly useful when importing LaTeX-based documents into Google Docs, such as content originally written in <a target="_blank" href="https://overleaf.com/">Overleaf</a> or other LaTeX editors.</p>
<p>Instead of manually reformatting equations, the add-on automatically renders LaTeX code into properly formatted math equations, preserving the typesetting and structure you’d expect from a LaTeX environment.</p>
<h3 id="heading-what-is-auto-latex-equations">What is Auto-LaTeX Equations?</h3>
<p><a target="_blank" href="https://workspace.google.com/marketplace/app/autolatex_equations/850293439076"><strong>Auto-LaTeX Equations</strong></a> is a free and open-source Google Docs add-on that scans your document for LaTeX expressions and converts them into a properly formatted equations.</p>
<p>It recognizes LaTeX code wrapped in these delimiters:</p>
<ul>
<li><p>Inline: <code>$$ ... $$</code></p>
</li>
<li><p>Display: <code>\[ ... \]</code></p>
</li>
</ul>
<p>Once detected, it renders the equations seamlessly within your document, eliminating the need to retype or manually format them.</p>
<ol>
<li><p>Paste your LaTeX expression into the Google Docs document. Make sure the expression is enclosed using one of the supported delimiters:</p>
<p> <code>$$ ... $$ or \[ ... \]</code></p>
</li>
<li><p>Open the add-on sidebar by clicking Extensions <strong>→</strong> Auto-LaTeX Equations <strong>→</strong> Start.</p>
</li>
<li><p>Once the sidebar opens, you’ll see a dropdown labeled “Delimiters” and a button called “Render Equations.”</p>
</li>
<li><p>Select the delimiter you used when enclosing your LaTeX equations – for example, <code>$$</code> or <code>\[ \]</code>.</p>
</li>
<li><p>Click the “Render Equations” button.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747203253430/e96fe9ac-ccba-4ed5-ab10-1e759d737d7d.png" alt="Auto Latex Equations add-on sidebar" class="image--center mx-auto" width="297" height="387" loading="lazy"></p>
<p>The add-on will automatically scan your document and convert all valid LaTeX expressions into properly formatted equation images.</p>
<p>This step-by-step process allows you to take any LaTeX-based math copied from ChatGPT and render it cleanly within Google Docs – ready for export to Word or PDF.</p>
<h3 id="heading-example-converting-a-latex-coded-equation-to-rendered-math-equations">Example: Converting a LaTeX coded Equation to Rendered Math Equations</h3>
<p>Paste the following equation into Google Docs:</p>
<p><code>$$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$</code></p>
<p>To convert it:</p>
<ol>
<li><p>Go to Extensions → Auto-LaTeX Equations → Start.</p>
</li>
<li><p>Select the Delimitor as <code>$$</code> ..<code>$$</code> and click on the Render Equations button. The equation will be rendered and look as follows:</p>
</li>
</ol>
<p>$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$</p><h4 id="heading-how-to-install-auto-latex-equations">How to Install Auto-LaTeX Equations</h4>
<ol>
<li><p>In Google Docs, click Extensions → Add-ons → Get add-ons.</p>
</li>
<li><p>Search for Auto-LaTeX Equations.</p>
</li>
<li><p>Click Install and follow the prompts.</p>
</li>
<li><p>After installation, access it from Extensions → Auto-LaTeX Equations.</p>
</li>
</ol>
<h2 id="heading-how-to-copy-math-equations-from-chatgpt-to-google-docs">How to Copy Math Equations from ChatGPT to Google Docs</h2>
<p>To easily transfer math equations and the surrounding content from ChatGPT into Google Docs without losing formatting, use the free <a target="_blank" href="https://chromewebstore.google.com/detail/chatgpt-to-google-docs-or/oibghjgooccojibfacdonaoipegckdeg"><strong>ChatGPT to Google Docs or PDF</strong></a> Chrome extension.</p>
<p>This extension allows you to:</p>
<ul>
<li><p>Export a single response (with equations and tables) into Google Docs while preserving formatting</p>
</li>
<li><p>Export an entire conversation, including math, code, and text, into a clean, one organized Google Docs, no need to export responses separately and <a target="_blank" href="https://www.freecodecamp.org/news/merge-multiple-google-docs-with-apps-script-or-google-docs-api/">merge multiple Google Docs into one</a> later</p>
</li>
<li><p>Save ChatGPT canvas content as a Google Docs or PDF</p>
</li>
<li><p>Export ChatGPT deep research documents directly into Google Docs</p>
</li>
<li><p>Export <a target="_blank" href="https://www.docstomarkdown.pro/chatgpt-to-pdf/">ChatGPT content directly into PDF format</a> when no further edits are necessary, eliminating the need to first export to Google Docs and then convert <a target="_blank" href="https://workspace.google.com/marketplace/app/docs_to_pdf_pro/302636103705">Google Docs to PDF</a></p>
</li>
</ul>
<p>It’s especially useful for students, researchers, and professionals who want to keep their AI-generated math, notes, and research well-organized in Google Docs or PDF format with minimal effort.</p>
<h2 id="heading-watch-how-to-write-equations-in-google-docs">Watch: How to Write Equations in Google Docs</h2>
<p>If you prefer visual learning, here’s a helpful video walkthrough that demonstrates all the methods discussed above – using the built-in equation editor, LaTeX-like commands, and the Auto-LaTeX Equations add-on.</p>
<p>This step-by-step tutorial covers:</p>
<ul>
<li><p>Opening and using the built-in equation toolbar</p>
</li>
<li><p>Typing LaTeX-style commands directly in the equation editor</p>
</li>
<li><p>Converting AI-generated LaTeX (e.g., from ChatGPT) into clean equations</p>
</li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Y_2q45Qscp0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-tips-for-formatting-math-equations-in-google-docs">Tips for Formatting Math Equations in Google Docs</h2>
<p><strong>Use inline equations when:</strong></p>
<ul>
<li><p>Inserting short expressions like <code>x²</code>, <code>a/b</code>, or single variables</p>
</li>
<li><p>Including math within a sentence to maintain the flow of text</p>
</li>
</ul>
<p><strong>Use block equations when:</strong></p>
<ul>
<li><p>Writing complex or multi-line formulas (e.g., the quadratic formula)</p>
</li>
<li><p>You want the equation to be clearly separated from the surrounding text for readability</p>
</li>
</ul>
<p><strong>Wrapping tips for rendered equations:</strong></p>
<ul>
<li><p>Rendered equations are treated as images in Google Docs, which may disrupt the document layout if not positioned correctly</p>
</li>
<li><p>To fix this:</p>
<ul>
<li><p>Click the equation image</p>
</li>
<li><p>Choose from:</p>
<ul>
<li><p><strong>In line</strong> – aligns the equation with surrounding text (best for inline use)</p>
</li>
<li><p><strong>Wrap text</strong> – wraps paragraph text around the equation image</p>
</li>
<li><p><strong>Break text</strong> – places the equation on its own line, isolating it</p>
</li>
</ul>
</li>
<li><p>Use the margin handles or spacing options to fine-tune the layout and prevent overlap or crowding</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Google Docs offers several flexible ways to write and manage math equations:</p>
<ul>
<li><p><strong>Use the built-in equation editor</strong> for basic symbols, fractions, exponents, and common operations. It’s easy to access and great for straightforward math tasks without needing special syntax.</p>
</li>
<li><p><strong>Try LaTeX-like commands</strong> inside the equation editor for faster input. You can type commands like <code>\frac</code>, <code>\sqrt</code>, or <code>\alpha</code> to quickly insert structured equations without navigating menus.</p>
</li>
<li><p><strong>Install add-ons like Auto-LaTeX Equations</strong> for advanced LaTeX rendering. This is especially useful if you're copying equations from Overleaf, ChatGPT, or LaTeX documents into Google Docs, as it preserves formatting and converts code into clean equation images.</p>
</li>
<li><p><strong>Use external tools when copying from other formats</strong>, like the <em>ChatGPT to Google Docs or PDF</em> Chrome extension, which helps retain equation formatting when moving content from ChatGPT or other platforms.</p>
</li>
</ul>
<p>Whether you’re completing math homework, preparing teaching materials, or writing a research paper, Google Docs, combined with these tools, gives you everything you need to create clear, professional-looking documents with math content.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Merge Multiple Google Docs into One ]]>
                </title>
                <description>
                    <![CDATA[ Merging multiple Google Docs into a single document is often essential for compiling reports, gathering information from various sources, or creating unified documents for presentations or sharing. By combining multiple files into one, users can keep... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/merge-multiple-google-docs-with-apps-script-or-google-docs-api/</link>
                <guid isPermaLink="false">672103feae01d783da13018b</guid>
                
                    <category>
                        <![CDATA[ Google Docs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ merging ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 29 Oct 2024 15:49:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730115525086/d5d63d7d-a5c0-4e16-868c-50901aebb248.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Merging multiple Google Docs into a single document is often essential for compiling reports, gathering information from various sources, or creating unified documents for presentations or sharing.</p>
<p>By combining multiple files into one, users can keep information organized, streamline collaboration, and simplify document handling for larger projects or recurring tasks.</p>
<p>But Google Docs lacks a built-in feature for merging multiple documents. This can make this process time-consuming if you’re trying to do it manually.</p>
<p>While there are add-ons available for <a target="_blank" href="https://workspace.google.com/marketplace/app/merge_docs_pro/61337277026">merging multiple Google Docs into one</a>, you can also create your own scripts using Google Apps Script or the Google Docs API for customized solutions. This approach gives you greater flexibility, letting you set up recurring document consolidation and manage high volumes of merges tailored to your specific needs.</p>
<p>In this tutorial, I’ll explain how to merge multiple Google Docs into one document using <a target="_blank" href="https://developers.google.com/apps-script">Apps Script</a> or the <a target="_blank" href="https://developers.google.com/docs/api/reference/rest">Google Docs API</a>.</p>
<h2 id="heading-how-to-merge-google-docs-using-google-apps-script">How to Merge Google Docs Using Google Apps Script</h2>
<p>Using Google Apps Script to merge multiple Google Docs is a straightforward way to automate document merging directly within Google Workspace.</p>
<p>This approach should work well for you if you need a simple solution that doesn’t require complex setups or external APIs. You can run Apps Script within Google Drive, making it easy to set up and execute directly from the browser.</p>
<p>Below is a step-by-step guide on how to use Google Apps Script for merging documents.</p>
<h3 id="heading-step-1-open-google-apps-script"><strong>Step 1: Open Google Apps Script</strong></h3>
<p>In Google Drive, click on <strong>New</strong> &gt; <strong>Google Apps Script</strong> to create a new script.</p>
<p>Then name the project something relevant, like “Document Merger.”</p>
<h3 id="heading-step-2-write-the-apps-script-code"><strong>Step 2: Write the Apps Script Code</strong></h3>
<p>Copy and paste the following code into the Apps Script editor. This script will create a new Google Doc and append content from each specified document.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeGoogleDocs</span>(<span class="hljs-params">docIds</span>) </span>{
  <span class="hljs-keyword">const</span> mergedDoc = DocumentApp.create(<span class="hljs-string">"Merged Document"</span>); <span class="hljs-comment">// Creates a new document</span>
  <span class="hljs-keyword">const</span> body = mergedDoc.getBody();

  docIds.forEach(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> doc = DocumentApp.openById(id);
    <span class="hljs-keyword">const</span> docBody = doc.getBody();

    <span class="hljs-comment">// Append content of each document to the merged document</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; docBody.getNumChildren(); i++) {
      <span class="hljs-keyword">const</span> element = docBody.getChild(i).copy(); <span class="hljs-comment">// Copy each element to preserve formatting</span>
      body.appendParagraph(element.getText());
    }
    body.appendPageBreak(); <span class="hljs-comment">// Add a page break after each document</span>
  });

  Logger.log(<span class="hljs-string">"Merged Document URL: "</span> + mergedDoc.getUrl());
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runMerge</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> docIds = [
    <span class="hljs-string">'DOCUMENT_ID_1'</span>, 
    <span class="hljs-string">'DOCUMENT_ID_2'</span>, 
    <span class="hljs-string">'DOCUMENT_ID_3'</span>
  ]; <span class="hljs-comment">// Replace with your actual document IDs</span>

  mergeGoogleDocs(docIds);
}
</code></pre>
<p><strong>Explanation of the Code:</strong></p>
<ul>
<li><p><strong>Creating the Merged Document</strong>: <code>DocumentApp.create("Merged Document")</code> creates a new Google Doc named "Merged Document," which will serve as the destination for all the content.</p>
</li>
<li><p><strong>Retrieving and Copying Content</strong>: <code>DocumentApp.openById(id)</code> opens each document in <code>docIds</code>, then retrieves its body content. The script copies each element, preserving its original formatting, and appends it to the new document.</p>
</li>
<li><p><strong>Adding Page Breaks</strong>: <code>body.appendPageBreak()</code> adds a page break after each document, helping maintain a clear separation between merged sections.</p>
</li>
<li><p><strong>Logging the Merged Document URL</strong>: The final URL of the merged document is logged, allowing you to access it directly from the Apps Script console.</p>
</li>
</ul>
<h3 id="heading-step-3-run-the-script"><strong>Step 3: Run the Script</strong></h3>
<p>First, you’ll want to save the script and authorize any required permissions.</p>
<p>Then in the Apps Script editor, select <code>runMerge()</code> as the function to run. Enter an array of document IDs you want to merge, like <code>['DOCUMENT_ID_1', 'DOCUMENT_ID_2', 'DOCUMENT_ID_3']</code>.</p>
<p>Finally, run the script, and it will create a merged document in your Google Drive. The URL will display in the console log.</p>
<h3 id="heading-how-to-customize-the-script"><strong>How to Customize the Script</strong></h3>
<p><strong>Order of Documents</strong>: The sequence in which documents are merged is controlled by the order of <code>docIds</code> in the array. Arrange these document IDs to define the exact order you want in the final document.</p>
<p>This approach is useful for structuring documents such as reports, books, or presentations, ensuring that chapters or sections appear in the intended flow.</p>
<p><strong>Adding Custom Formatting</strong>: The script can be customized to add specific formatting to each section of the merged document. You can insert headers or footers to distinguish each document, include page breaks, or set up consistent styling for fonts, sizes, and colors.</p>
<p>For example, you can add headers programmatically at the start of each new document in the merge, helping create a cohesive structure.</p>
<p><strong>Handling Specific Elements</strong>: Apps Script supports detailed customization to merge only certain types of content, like text, images, or tables, while skipping others. You can adjust the script to filter out elements by type or to prioritize specific formats.</p>
<p>For instance, to create a visually appealing document, you might choose to merge only text and images while excluding tables or unsupported elements. This approach provides a more polished final document by focusing on the content types you need most.</p>
<h3 id="heading-when-to-use-google-apps-script-for-merging"><strong>When to Use Google Apps Script for Merging</strong></h3>
<p>Google Apps Script is ideal if you want a simple, in-drive solution without needing to set up external API access. It’s especially useful for quick merges or individual projects within Google Workspace, and it provides enough flexibility to handle most standard document formats and structures.</p>
<p>For more complex requirements, such as merging across other platforms or integrating with external tools, consider using the Google Docs API explained in the next section.</p>
<h2 id="heading-how-to-merge-google-docs-using-the-google-docs-api">How to Merge Google Docs Using the Google Docs API</h2>
<p>Combining Google Docs using the Google Docs API allows you to programmatically combine content from multiple documents into one unified file. This is ideal for automating repetitive merges or creating customized documents on demand.</p>
<p>This approach is powerful for users who need precise control over document content, formatting, and layout, making it suitable for larger workflows or integrations within other applications.</p>
<p>Below is a detailed, step-by-step guide on how to use the Google Docs API to merge multiple Google Docs into one.</p>
<h3 id="heading-step-1-enable-the-google-docs-api"><strong>Step 1: Enable the Google Docs API</strong></h3>
<p>First, go to the <a target="_blank" href="https://console.cloud.google.com/">Google Cloud Console</a>. Create a new project or select an existing one.</p>
<p>In the API Library, search for "Google Docs API" and enable it for your project.</p>
<p>Next, create OAuth 2.0 credentials by going to <strong>APIs &amp; Services</strong> &gt; <strong>Credentials</strong>. Choose <strong>Create Credentials</strong> &gt; <strong>OAuth client ID</strong> and configure this for a Web Application if you plan to integrate it into Web services.</p>
<h3 id="heading-step-2-install-the-googleapis-client-library"><strong>Step 2: Install the</strong> <code>googleapis</code> <strong>Client Library</strong></h3>
<p>In a Node.js environment, you’ll need the <code>googleapis</code> package to interact with the Google Docs API. Install it by running:</p>
<pre><code class="lang-bash">npm install googleapis
</code></pre>
<h3 id="heading-step-3-write-the-script-to-merge-google-docs"><strong>Step 3: Write the Script to Merge Google Docs</strong></h3>
<p>The following script uses the Google Docs API to create a new document, retrieve content from each source document, and then append this content to the new document.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { google } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'googleapis'</span>);
<span class="hljs-keyword">const</span> docs = google.docs(<span class="hljs-string">'v1'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeGoogleDocs</span>(<span class="hljs-params">auth, docIds</span>) </span>{
  <span class="hljs-comment">// Step 3a: Create a new document that will serve as the merged document</span>
  <span class="hljs-keyword">const</span> newDoc = <span class="hljs-keyword">await</span> docs.documents.create({
    auth,
    <span class="hljs-attr">requestBody</span>: { <span class="hljs-attr">title</span>: <span class="hljs-string">'Merged Document'</span> },
  });
  <span class="hljs-keyword">const</span> newDocId = newDoc.data.documentId;

  <span class="hljs-comment">// Step 3b: Loop through each document ID, retrieving content and appending it to the new document</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> docId <span class="hljs-keyword">of</span> docIds) {
    <span class="hljs-comment">// Retrieve the document's body content</span>
    <span class="hljs-keyword">const</span> doc = <span class="hljs-keyword">await</span> docs.documents.get({
      auth,
      <span class="hljs-attr">documentId</span>: docId,
    });

    <span class="hljs-comment">// Prepare each content element as a request for the new document</span>
    <span class="hljs-keyword">const</span> requests = doc.data.body.content.map(<span class="hljs-function">(<span class="hljs-params">element</span>) =&gt;</span> ({
      <span class="hljs-attr">insertText</span>: {
        <span class="hljs-attr">text</span>: element.paragraph?.elements?.[<span class="hljs-number">0</span>]?.textRun?.content || <span class="hljs-string">''</span>,
        <span class="hljs-attr">location</span>: { <span class="hljs-attr">index</span>: <span class="hljs-number">1</span> }, <span class="hljs-comment">// Append to the start of the document, shift with each insertion</span>
      },
    }));

    <span class="hljs-comment">// Send a batch update request to insert all elements into the new document</span>
    <span class="hljs-keyword">await</span> docs.documents.batchUpdate({
      auth,
      <span class="hljs-attr">documentId</span>: newDocId,
      <span class="hljs-attr">requestBody</span>: { requests },
    });
  }

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Merged Document URL: https://docs.google.com/document/d/<span class="hljs-subst">${newDocId}</span>`</span>);
}
</code></pre>
<p><strong>Explanation of the Code:</strong></p>
<ol>
<li><p><strong>Creating the Merged Document</strong>: <code>docs.documents.create()</code> creates a new Google Doc titled "Merged Document." This document ID (<code>newDocId</code>) will serve as the destination where content from each document is appended.</p>
</li>
<li><p><strong>Retrieving Content</strong>: The <code>docs.documents.get()</code> method fetches each document’s content based on its ID. This retrieves all elements from the document body, such as paragraphs, images, and other supported elements.</p>
</li>
<li><p><strong>Preparing Insert Requests</strong>: The <code>map()</code> function converts each document element into an <code>insertText</code> request. Each request specifies the text and the location in the new document where it should be added.</p>
</li>
<li><p><strong>Appending Text in Sequence</strong>: The <code>batchUpdate</code> method takes a set of requests and applies them sequentially to the new document. Here, the location index starts at 1 (the beginning of the document) and shifts with each new insertion to prevent overwriting.</p>
</li>
</ol>
<h3 id="heading-step-4-run-the-script"><strong>Step 4: Run the Script</strong></h3>
<p>Now you’ll initialize the <code>auth</code> variable with <a target="_blank" href="https://developers.google.com/identity/protocols/oauth2">OAuth 2.0 credentials</a>, which authenticates access to the Docs API.</p>
<p>Then you’ll need to call the <code>mergeGoogleDocs</code> function, passing the <code>auth</code> object and an array of document IDs.</p>
<p>Once the script runs, it will output a URL for the merged document, which you can access directly in Google Docs.</p>
<h3 id="heading-customization-and-additional-options"><strong>Customization and Additional Options</strong></h3>
<ul>
<li><p><strong>Order of Insertion</strong>: Control the order in which document content is appended by arranging the document IDs in <code>docIds</code>.</p>
</li>
<li><p><strong>Formatting</strong>: The Google Docs API can support additional formatting, such as bold or italic text, by modifying the insert requests. This can be achieved with advanced requests using the <code>updateTextStyle</code> API method.</p>
</li>
<li><p><strong>Element Types</strong>: The script currently handles only text paragraphs. To merge other elements like images or tables, extend the script to support more element types by using conditional checks on the <code>element</code> structure.</p>
</li>
</ul>
<h3 id="heading-when-to-use-google-docs-api-for-merging"><strong>When to Use Google Docs API for Merging</strong></h3>
<p>The Google Docs API is ideal if you need precise control over document structure, element-specific formatting, and larger-scale automation for merging.</p>
<p>This approach is especially useful when handling complex formatting requirements, such as custom headers, lists, or tables, and allows for seamless integration with external applications or workflows outside Google Workspace.</p>
<p>If you have high-volume merge needs or you’re looking to incorporate merging into broader, automated processes, the Google Docs API provides advanced flexibility and customization options beyond what Google Apps Script can offer.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, merging Google Docs is crucial for organizing and streamlining document management. While Google Docs lacks a built-in feature for this, you can leverage Google Apps Script for straightforward automation or the Google Docs API for more advanced, large-scale merging.</p>
<p>For those seeking a user-friendly solution without the need for coding, <a target="_blank" href="https://www.mergedocs.pro/"><strong>Merge Docs Pro</strong></a> provides an intuitive interface to combine multiple Google Docs into one document. It simplifies document consolidation, enhances collaboration, and saves time, making it an excellent choice if you’re looking to streamline your workflow within Google Workspace.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Merge Word Files Using NodeJS ]]>
                </title>
                <description>
                    <![CDATA[ Merging Word files is essential for applications like document automation, where multiple reports, proposals, or forms need to be consolidated into a single document. Content management systems also rely on this functionality to combine documents for... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-merge-word-files-using-nodejs/</link>
                <guid isPermaLink="false">670e96e0c569cebb75e363e6</guid>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 15 Oct 2024 16:22:56 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728997884597/9eb261f8-b299-4f43-bd0d-e2122b2c0c7b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Merging Word files is essential for applications like document automation, where multiple reports, proposals, or forms need to be consolidated into a single document.</p>
<p>Content management systems also rely on this functionality to combine documents for collaborative editing or archival.</p>
<p><a target="_blank" href="https://nodejs.org/en">Node.js</a> is a good choice for such tasks because it supports both server-side and client-side operations, allowing for efficient document handling in various environments.</p>
<p>In this tutorial, I'll explain how to <a target="_blank" href="https://www.mergedocs.pro/merge-word-documents">merge Word documents</a> using <a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-an-event-app-with-node-js/">web applications developed in Node.js</a>.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ol>
<li><p><strong>Node.js</strong> and <strong>npm</strong> – Ensure both are installed to manage dependencies.</p>
</li>
<li><p><strong>Libraries</strong> – The following libraries are required:</p>
<ul>
<li><p><code>docx-merger</code> for server-side merging of Word files.</p>
</li>
<li><p><code>mammoth</code> for converting <code>.docx</code> to HTML, useful for client-side merging.</p>
</li>
<li><p><code>html-docx-js</code> (or a similar library) for converting HTML back to <code>.docx</code>.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-method-1-server-side-merging-using-docx-merger">Method 1: Server-Side Merging Using <code>docx-merger</code></h2>
<p><a target="_blank" href="https://www.npmjs.com/package/docx-merger"><code>docx-merger</code></a> is a specialized <a target="_blank" href="https://www.freecodecamp.org/news/node-js-basics/">Node.js</a> library designed to merge multiple <code>.docx</code> files by directly combining their content, including text, tables, and other common elements, into a single cohesive document. It’s particularly useful when you need to retain the original structure and formatting across merged documents.</p>
<p>Here’s how the docx-merger works and why it’s effective for server side merging:</p>
<ul>
<li><p><strong>Direct Merging of</strong> <code>.docx</code> Elements: <code>docx-merger</code> reads the underlying XML structure of each <code>.docx</code> file and combines them at the document level. This preserves the layout, styles, headers, footers, and even complex structures like tables and images, so the output maintains the appearance of the original files.</p>
</li>
<li><p><strong>Configurable Merging Options</strong>: The library offers flexibility in merging. You can specify whether to combine entire documents or selectively merge specific sections. This is particularly useful for use cases where only parts of the documents need to be merged, such as appending summaries, adding title pages, or combining sections from multiple reports.</p>
</li>
<li><p><strong>Handling Embedded Objects</strong>: <code>docx-merger</code> supports embedded elements such as images, shapes, and other media. When merging, it retains these objects, ensuring that visual elements aren’t lost or distorted in the output. This is crucial for reports, presentations, and other documents where graphics play a significant role.</p>
</li>
<li><p><strong>Simplified API for Integration</strong>: The API for <code>docx-merger</code> is straightforward, making it easy to incorporate into Node.js applications. You initialize the library with the documents you want to merge, configure any merging options, and then output the result as a <code>.docx</code> file. This ease of use makes it simple to add document merging to existing workflows, whether as a standalone script or as part of a larger document processing pipeline.</p>
</li>
</ul>
<p>Using <code>docx-merger</code>, you can efficiently merge large volumes of documents with confidence that their original formatting and content will be preserved, making it an ideal choice for server-side document processing in Node.js.</p>
<h3 id="heading-setting-up-docx-merger"><strong>Setting Up</strong> <code>docx-merger</code><strong>:</strong></h3>
<p>To start, install <code>docx-merger</code> via npm:</p>
<pre><code class="lang-javascript">npm install docx-merger
</code></pre>
<p>This library requires no additional setup beyond installation. Once installed, you can import it and initialize a new instance to start merging files.</p>
<p>It works by reading each <code>.docx</code> file as a buffer, and then combining them into one output file.</p>
<h3 id="heading-merging-files-with-docx-merger"><strong>Merging Files with</strong> <code>docx-merger</code><strong>:</strong></h3>
<p>Follow the below steps to merge docx files using <code>docx-merge</code>:</p>
<ol>
<li><p>First, import <code>fs</code> to handle file reading and <code>docx-merger</code> for merging.</p>
</li>
<li><p>Initialize <code>docx-merger</code> with an empty configuration object and an array of file buffers to merge.</p>
</li>
<li><p>Use the <code>.save()</code> method to merge and <a target="_blank" href="https://www.freecodecamp.org/news/how-to-read-and-write-files-with-nodejs/">save the resulting file as a buffer</a>, then write it to disk using <code>fs.writeFileSync()</code>.</p>
</li>
</ol>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">const</span> DocxMerger = <span class="hljs-built_in">require</span>(<span class="hljs-string">'docx-merger'</span>);

<span class="hljs-keyword">const</span> files = [fs.readFileSync(<span class="hljs-string">'file1.docx'</span>), fs.readFileSync(<span class="hljs-string">'file2.docx'</span>)];

<span class="hljs-keyword">const</span> docxMerger = <span class="hljs-keyword">new</span> DocxMerger({}, files);

docxMerger.save(<span class="hljs-string">'nodebuffer'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {

 fs.writeFileSync(<span class="hljs-string">'merged.docx'</span>, data);

});
</code></pre>
<p>This example reads <code>file1.docx</code> and <code>file2.docx</code> as buffers, merges them, and saves the merged document as <code>merged.docx</code>.</p>
<h3 id="heading-use-cases-for-server-side-merging"><strong>Use Cases for Server-side Merging:</strong></h3>
<p>Server-side merging with <code>docx-merger</code> is ideal for scenarios that require high-volume processing or automation. For example:</p>
<ol>
<li><p><strong>Batch Document Processing</strong>: Automating the merging of invoices, reports, or records for large data sets.</p>
</li>
<li><p><strong>Automated Document Workflows</strong>: Consolidating different sections of a document from various sources for workflows like report generation or archival.</p>
</li>
<li><p><strong>Backend Services</strong>: Running in server environments where the user interacts indirectly, such as merging documents through an API or a scheduled backend task.</p>
</li>
</ol>
<h2 id="heading-method-2-client-side-merging-with-mammoth-and-html-conversion">Method 2: Client-Side Merging with <code>mammoth</code> and HTML Conversion</h2>
<p><a target="_blank" href="https://www.npmjs.com/package/mammoth"><code>mammoth</code></a> is a Node.js library that <a target="_blank" href="https://www.docstomarkdown.pro/convert-word-to-html/">converts word files into HTML</a>, making it ideal for client-side applications that require real-time document manipulation. This approach is particularly useful for scenarios where users need to edit or combine documents directly in the browser before exporting them.</p>
<p>Here’s what makes <code>mammoth</code> a powerful tool for client-side document handling:</p>
<ul>
<li><p><strong>High-Fidelity</strong> – <code>.docx</code> to HTML Conversion: <code>mammoth</code> translates <code>.docx</code> content into clean, semantic HTML, preserving essential formatting like headings, paragraphs, and lists. This ensures that the converted documents retain their original structure and are easy to manipulate in a web environment.</p>
</li>
<li><p><strong>Embedded Image Handling with Base64</strong> – When <code>mammoth</code> encounters embedded images in a <code>.docx</code> file, it encodes them as Base64 and includes them in <code>&lt;img&gt;</code> tags within the HTML output. This allows images to be seamlessly displayed, merged, or manipulated alongside text, making the final document more cohesive and visually accurate when re-exported to <code>.docx</code>.</p>
</li>
<li><p><strong>Dynamic Document Editing</strong> – Because <code>mammoth</code> outputs HTML, it’s easy to add or adjust document content on the client side using JavaScript or client-side frameworks. Users can combine multiple HTML snippets from different <code>.docx</code> files, rearrange sections, or even inject new content dynamically, which is valuable for applications that require real-time content customization.</p>
</li>
<li><p><strong>Conversion Back to</strong> <code>.docx</code> with <code>html-docx-js</code> – After creating or editing a document in HTML, you can convert it back into <code>.docx</code> format using libraries like <code>html-docx-js</code>. This library takes the merged HTML content and generates a downloadable <code>.docx</code> file, making it straightforward to return the final document to the user in the original format.</p>
</li>
</ul>
<p>Using <code>mammoth</code> for client-side merging offers a flexible, interactive way to manage document content in the browser, with features that support both text and images. Combined with <code>html-docx-js</code> or a similar tool, you can build powerful applications that allow users to customize and merge documents on the fly, then export their work as <code>.docx</code> files.</p>
<h3 id="heading-converting-docx-to-html-with-mammoth"><strong>Converting</strong> <code>.docx</code> <strong>to HTML with</strong> <code>mammoth</code></h3>
<p>First, install <code>mammoth</code>:</p>
<pre><code class="lang-javascript">npm install mammoth
</code></pre>
<p>After installation, <code>mammoth</code> can be used to convert <code>.docx</code> files to HTML, which allows for easy merging of document content, including images, by manipulating the HTML output.</p>
<p><strong>Example code to convert</strong> <code>.docx</code> <strong>files to HTML:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> mammoth <span class="hljs-keyword">from</span> <span class="hljs-string">'mammoth'</span>;

<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">convertDocxToHtml</span>(<span class="hljs-params">filePath</span>) </span>{

 <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> mammoth.convertToHtml({ <span class="hljs-attr">path</span>: filePath });

 <span class="hljs-keyword">return</span> result.value;

}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeHtmlFiles</span>(<span class="hljs-params"></span>) </span>{

 <span class="hljs-keyword">const</span> html1 = <span class="hljs-keyword">await</span> convertDocxToHtml(<span class="hljs-string">'file1.docx'</span>);

 <span class="hljs-keyword">const</span> html2 = <span class="hljs-keyword">await</span> convertDocxToHtml(<span class="hljs-string">'file2.docx'</span>);

 <span class="hljs-keyword">const</span> mergedHtml = html1 + html2;

 <span class="hljs-keyword">return</span> mergedHtml;

}

<span class="hljs-keyword">const</span> mergedHtmlContent = <span class="hljs-keyword">await</span> mergeHtmlFiles();
</code></pre>
<p>In this example, <code>convertDocxToHtml</code> reads a <code>.docx</code> file and converts it into HTML format. <code>mammoth</code> automatically converts any images in the document into Base64-encoded data URLs, so they can be merged and displayed alongside text.</p>
<h3 id="heading-merging-html-with-images-and-converting-back-to-docx"><strong>Merging HTML with Images and Converting Back to</strong> <code>.docx</code><strong>:</strong></h3>
<p>Once the HTML content is merged, including any Base64-encoded images, you can use <a target="_blank" href="https://www.npmjs.com/package/html-docx-js"><code>html-docx-js</code></a> to convert it back into <code>.docx</code> format. This process ensures that both text and images are preserved in the final output.</p>
<p><strong>Install</strong> <code>html-docx-js</code><strong>:</strong></p>
<pre><code class="lang-javascript">npm install html-docx-js
</code></pre>
<p>Then, use the library to wrap the merged HTML and convert it back to <code>.docx</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> htmlDocx <span class="hljs-keyword">from</span> <span class="hljs-string">'html-docx-js'</span>;

<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>;

<span class="hljs-keyword">const</span> wrappedHtmlContent = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>${mergedHtmlContent}<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>;

<span class="hljs-keyword">const</span> docxBuffer = htmlDocx.asBlob(wrappedHtmlContent);

fs.writeFileSync(<span class="hljs-string">'merged_with_images.docx'</span>, docxBuffer);
</code></pre>
<p>In this code, the merged HTML content, which contains text and images, is wrapped in a basic HTML structure and then passed to <code>htmlDocx.asBlob()</code>. This function generates a <code>.docx</code> buffer, retaining both text and images, which is then saved as a <code>.docx</code> file on disk.</p>
<h3 id="heading-use-cases-for-image-handling-in-client-side-merging"><strong>Use Cases for Image Handling in Client-Side Merging:</strong></h3>
<p>Client-side merging with <code>mammoth</code> and <code>html-docx-js</code> is useful for:</p>
<ol>
<li><p><strong>Real-Time Document Editing</strong>: Interactive applications where users can upload, merge, and download <code>.docx</code> files directly within the browser, complete with embedded images.</p>
</li>
<li><p><strong>Collaborative Platforms</strong>: Tools for collaborative document creation, where users need to merge <code>.docx</code> files and keep images intact.</p>
</li>
<li><p><strong>Custom Document Generators</strong>: Applications generating documents with both text and images from multiple <code>.docx</code> files, such as customized reports, ensuring that all elements are retained in the final output.</p>
</li>
</ol>
<p>This method provides a comprehensive solution for client-side document merging, allowing for flexible handling of rich content in various use cases.</p>
<h2 id="heading-error-handling-and-best-practices">Error Handling and Best Practices</h2>
<p>Merging Word files can present several challenges, particularly with formatting and error management. Here are key issues, along with <a target="_blank" href="https://www.freecodecamp.org/news/effective-error-handling-in-react-applications/">error handling</a> tips:</p>
<h3 id="heading-common-issues-and-error-handling"><strong>Common Issues and Error Handling</strong></h3>
<ol>
<li><p><strong>Layout Inconsistencies</strong>: HTML conversion may lead to unexpected formatting differences when converting back to <code>.docx</code>.</p>
</li>
<li><p><strong>Styling Differences</strong>: Custom styles in <code>.docx</code> may not translate correctly to HTML, resulting in font and margin discrepancies. Always validate that each file is converted properly, and apply a consistent style sheet to minimize inconsistencies.</p>
</li>
<li><p><strong>Image Formatting</strong>: Base64-encoded images might not render correctly in the final <code>.docx</code>, similar to challenges in <a target="_blank" href="https://www.mergedocs.pro/merge-pdf-files">merging PDF files</a>. Ensure that all images are properly formatted before the merge, and check for issues during the conversion.</p>
</li>
</ol>
<h3 id="heading-best-practices"><strong>Best Practices</strong></h3>
<ol>
<li><p><strong>Consistent Formatting</strong>: Normalize styles across documents using a predefined stylesheet to minimize inconsistencies.</p>
</li>
<li><p><strong>Data Integrity</strong>: Validate that each file is read and converted correctly by checking the output of each conversion.</p>
</li>
<li><p><strong>Encoding and Format Checks</strong>: Confirm all files are in the expected <code>.docx</code> format and that Base64 images are correctly formatted to ensure successful conversions.</p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>The two methods for merging Word files with Node.js—using <code>docx-merger</code> for server-side merging and <code>mammoth</code> with HTML conversion for client-side merging—provide flexibility for various use cases:</p>
<p><strong>Server-Side Merging (docx-merger):</strong></p>
<ul>
<li><p>Ideal for batch processing and automated workflows.</p>
</li>
<li><p>Suitable for high-volume document merging without user interaction.</p>
</li>
<li><p>Works effectively with frameworks like Express.js and NestJS, allowing seamless integration into backend services for processing multiple files.</p>
</li>
</ul>
<p><strong>Client-Side Merging (mammoth and HTML Conversion):</strong></p>
<ul>
<li><p>Best for interactive, real-time applications where users manipulate documents directly.</p>
</li>
<li><p>Supports dynamic editing and combining of documents in the browser.</p>
</li>
<li><p>Works well with frameworks like Astro.js, React, or Vue.js, facilitating smooth integration into modern web applications.</p>
</li>
</ul>
<p>To extend this functionality, consider the following steps:</p>
<ul>
<li><p>Integrate these methods into a larger application or web service where users can upload and merge documents directly.</p>
</li>
<li><p>Optimize performance for high-usage environments by exploring:</p>
<ul>
<li><p>File caching to reduce redundant processing.</p>
</li>
<li><p>Optimizing the conversion process for speed and efficiency.</p>
</li>
<li><p>Load balancing for server-side implementations to handle multiple requests.</p>
</li>
</ul>
</li>
</ul>
<p>By following best practices and ensuring robust error handling, you can create a reliable and scalable solution for merging <code>.docx</code> files with Node.js.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Merge Word Documents in Python – Three Effective Methods with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In today's fast-paced work environment, automation is crucial for optimizing your repetitive tasks and enhancing your productivity. Deploying Python functions to automate the merging of multiple Word documents into a single, cohesive file can help yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/merge-word-documents-in-python/</link>
                <guid isPermaLink="false">66bb959b6a3faffa7d146ab7</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ automation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ docs ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 13 Aug 2024 17:19:23 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723552225928/558a428b-d6a1-487c-a563-5aa6bee8e029.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In today's fast-paced work environment, automation is crucial for optimizing your repetitive tasks and enhancing your productivity.</p>
<p>Deploying Python functions to automate the merging of multiple Word documents into a single, cohesive file can help you streamline your document management processes. This approach not only saves time but also ensures consistent and accurate deliverables.</p>
<p>By integrating these automated processes into your workflows, such as during build triggers or scheduled tasks, you and your team can further enhance efficiency and reduce manual effort.</p>
<p>In this article, we’ll explore three effective methods for <a target="_blank" href="https://www.docstomarkdown.pro/combine-multiple-word-documents-into-one/">merging multiple Word documents into one</a>: <code>docxcompose</code>, <code>pypandoc</code>, and <code>python-docx</code>. Each method has its unique strengths and is suited for different use cases.</p>
<h2 id="heading-1-how-to-merge-documents-with-docxcompose">1. How to Merge Documents with <code>docxcompose</code></h2>
<p><a target="_blank" href="https://pypi.org/project/docxcompose/"><code>docxcompose</code></a> is a specialized Python library designed explicitly for <a target="_blank" href="https://workspace.google.com/marketplace/app/merge_docs_pro/61337277026">merging Word documents</a> while preserving their complex formatting and structural elements.</p>
<p>Unlike general-purpose libraries, <code>docxcompose</code> focuses on maintaining document integrity during the merge process. This makes it the right choice for tasks where preserving headers, footers, and custom styles is essential.</p>
<p><strong>Key Features</strong></p>
<ol>
<li><p><strong>Preserves Complex Formatting</strong> – Ensures that headers, footers, and styles from each document are retained in the final merged output.</p>
</li>
<li><p><strong>Sequential Merging</strong> – Allows for appending multiple documents in a specified order, making it suitable for structured document assembly.</p>
</li>
<li><p><strong>Easy Integration</strong> – Designed to work seamlessly with the <code>python-docx</code> library, making it easy to incorporate into existing workflows.</p>
</li>
<li><p><strong>Processing Time</strong> – <code>docxcompose</code> is optimized for merging large documents while preserving complex formatting and styles. It processes documents sequentially, which can lead to slower performance for very large documents.</p>
</li>
<li><p><strong>Memory Usage</strong> – <code>docxcompose</code> requires moderate memory usage, as it needs to store the merged document in memory before saving it to disk.</p>
</li>
</ol>
<h3 id="heading-docxcompose-use-case"><code>docxcompose</code> Use Case</h3>
<p>Use <code>docxcompose</code> when:</p>
<ol>
<li><p>You need to combine DOCX files while preserving detailed formatting and layout elements.</p>
</li>
<li><p>You are dealing with documents that include various styles, headers, footers, or other advanced formatting features.</p>
</li>
<li><p>Your primary goal is to merge documents without losing any of their original formatting or structure.</p>
</li>
</ol>
<h3 id="heading-how-to-install-docxcompose">How to Install <code>docxcompose</code></h3>
<p>To use <code>docxcompose</code>, install the library with the following command:</p>
<pre><code class="lang-python">pip install docxcompose
</code></pre>
<h3 id="heading-example-code">Example Code</h3>
<p>Here’s a Python script that uses <code>docxcompose</code> to merge multiple DOCX files:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> docxcompose.composer <span class="hljs-keyword">import</span> Composer
<span class="hljs-keyword">from</span> docx <span class="hljs-keyword">import</span> Document

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">merge_docs</span>(<span class="hljs-params">output_path, *input_paths</span>):</span>

    base_doc = Document(input_paths[<span class="hljs-number">0</span>])
    composer = Composer(base_doc)


    <span class="hljs-keyword">for</span> file_path <span class="hljs-keyword">in</span> input_paths[<span class="hljs-number">1</span>:]:
        doc = Document(file_path)
        composer.append(doc)

    composer.save(output_path)
    print(<span class="hljs-string">f"Documents merged successfully into <span class="hljs-subst">{output_path}</span>"</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    output_file = <span class="hljs-string">"merged_document.docx"</span>
    input_files = [<span class="hljs-string">"doc1.docx"</span>, <span class="hljs-string">"doc2.docx"</span>, <span class="hljs-string">"doc3.docx"</span>]
    merge_docs(output_file, *input_files)
</code></pre>
<p>In this code:</p>
<ol>
<li><p><code>Composer</code> – Manages the merging process by taking an initial document and appending additional documents while retaining their formatting.</p>
</li>
<li><p><code>append</code> – Adds each subsequent document’s content to the base document, preserving the original layout and styles.</p>
</li>
<li><p><code>save</code> – Finalizes and saves the merged document to the specified output path.</p>
</li>
</ol>
<h3 id="heading-how-to-add-page-breaks-with-docxcompose">How to Add Page Breaks with <code>docxcompose</code></h3>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Page_break">Page breaks</a> help maintain a clear separation between sections, enhancing the document's organization and readability.</p>
<p>With <code>docxcompose</code>, you can ensure that each appended document begins on a new page, which improves the final document’s structure and navigation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> docxcompose.composer <span class="hljs-keyword">import</span> Composer
<span class="hljs-keyword">from</span> docx <span class="hljs-keyword">import</span> Document

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">merge_docs_with_page_breaks</span>(<span class="hljs-params">output_path, *input_paths</span>):</span>

    base_doc = Document(input_paths[<span class="hljs-number">0</span>])
    composer = Composer(base_doc)


    <span class="hljs-keyword">for</span> file_path <span class="hljs-keyword">in</span> input_paths[<span class="hljs-number">1</span>:]:
        doc = Document(file_path)

        <span class="hljs-comment"># adding page break before merging each document</span>
        base_doc.add_page_break()
        composer.append(doc)

    composer.save(output_path)
    print(<span class="hljs-string">f"Documents merged successfully into <span class="hljs-subst">{output_path}</span>"</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    output_file = <span class="hljs-string">"merged_document_with_page_breaks.docx"</span>
    input_files = [<span class="hljs-string">"doc1.docx"</span>, <span class="hljs-string">"doc2.docx"</span>, <span class="hljs-string">"doc3.docx"</span>]
    merge_docs_with_page_breaks(output_file, *input_files)
</code></pre>
<p><strong>Note:</strong> You can also use the same method to <a target="_blank" href="https://www.docstomarkdown.pro/merge-multiple-google-docs-into-one-and-export/">merge multiple Google Docs into one</a> by first exporting the Google Docs as Word documents.</p>
<h2 id="heading-2-how-to-merge-documents-with-pypandoc">2. How to Merge Documents with <code>pypandoc</code></h2>
<p><a target="_blank" href="https://pypi.org/project/pypandoc/"><code>pypandoc</code></a> is a powerful tool that leverages <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-pandoc/">Pandoc</a> to convert and merge documents across a wide range of formats.</p>
<p>Pandoc is known for its versatility in handling document conversions, and <code>pypandoc</code> extends this capability to Python, enabling the integration of documents from different sources and formats.</p>
<p><strong>Key Features:</strong></p>
<ol>
<li><p><strong>Cross-Format Conversion</strong> – Supports conversion between various formats such as DOCX, Markdown, HTML, and more.</p>
</li>
<li><p><strong>Unified Output</strong> – Allows you to merge content from diverse formats into a single DOCX file, making it useful for integrating documents created with different tools.</p>
</li>
<li><p><strong>Text-Based Merging</strong> – Converts documents to plain text for merging and then back to DOCX, simplifying the integration process.</p>
</li>
<li><p><strong>Processing Time</strong> – <code>pypandoc</code> is generally faster than <code>docxcompose</code> for merging documents, as it uses Pandoc's conversion capabilities to simplify the merging process. But it may be slower for very large documents or those with complex formatting.</p>
</li>
<li><p><strong>Memory Usage</strong> – <code>pypandoc</code> requires less memory usage compared to <code>docxcompose</code>, as it converts documents to plain text before merging, reducing the memory footprint.</p>
</li>
</ol>
<h3 id="heading-pypandoc-use-case"><code>pypandoc</code> Use Case</h3>
<p>Use <code>pypandoc</code> when:</p>
<ol>
<li><p>You need to merge documents in different formats (for example, DOCX, Markdown, HTML) into a single Word file.</p>
</li>
<li><p>You are working with content from various sources and need to produce a unified output.</p>
</li>
<li><p>You require a flexible solution for document integration that handles format conversions.</p>
</li>
</ol>
<h3 id="heading-how-to-install-pypandoc">How to Install <code>pypandoc</code></h3>
<p>Install <code>pypandoc</code> using the following command:</p>
<pre><code class="lang-python">pip install pypandoc
</code></pre>
<h3 id="heading-example-code-1">Example Code</h3>
<p>Here’s a Python script that uses <code>pypandoc</code> to merge documents from different formats into a single DOCX file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pypandoc
<span class="hljs-keyword">import</span> os

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">merge_docs</span>(<span class="hljs-params">output_path, *input_paths</span>):</span>
    all_text = <span class="hljs-string">""</span>
    <span class="hljs-keyword">for</span> file_path <span class="hljs-keyword">in</span> input_paths:
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isfile(file_path):
            print(<span class="hljs-string">f"File not found: <span class="hljs-subst">{file_path}</span>"</span>)
            <span class="hljs-keyword">continue</span>

        text = pypandoc.convert_file(file_path, <span class="hljs-string">'plain'</span>)
        all_text += text + <span class="hljs-string">"\n\n"</span>


    doc = pypandoc.convert_text(all_text, <span class="hljs-string">'docx'</span>, format=<span class="hljs-string">'md'</span>)
    <span class="hljs-keyword">with</span> open(output_path, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> f:
        f.write(doc)

    print(<span class="hljs-string">f"Documents merged successfully into <span class="hljs-subst">{output_path}</span>"</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    output_file = <span class="hljs-string">"merged_document.docx"</span>
    input_files = [<span class="hljs-string">"doc1.md"</span>, <span class="hljs-string">"doc2.html"</span>, <span class="hljs-string">"doc3.docx"</span>]
    merge_docs(output_file, *input_files)
</code></pre>
<p>In this code:</p>
<ol>
<li><p><code>convert_file</code> – Converts each document to plain text, which simplifies the merging process by removing formatting.</p>
</li>
<li><p><code>convert_text</code> – Converts the combined plain text back to DOCX format, allowing for a unified final document.</p>
</li>
</ol>
<p><code>pypandoc</code> also allows multiple other document operations such as converting DOCX files to Markdown, enabling you to automate publishing Word or <a target="_blank" href="https://workspace.google.com/marketplace/app/docs_to_wordpress_pro/346830534164">Google Docs to WordPress</a> or any other CMS.</p>
<p><strong>Caution:</strong> While <code>pypandoc</code> is effective for converting and merging documents, be aware that formatting may be lost during the process. The text-based merging approach <strong>may not</strong> preserve all original styles, headers, or other formatting details from the source documents.</p>
<h2 id="heading-3-how-to-merge-documents-with-python-docx">3. How to Merge Documents with <code>python-docx</code></h2>
<p><a target="_blank" href="https://pypi.org/project/python-docx/"><code>python-docx</code></a> is a widely used library for creating, reading, and <a target="_blank" href="https://www.freecodecamp.org/news/how-to-delete-a-page-in-word-remove-blank-or-extra-pages/">manipulating DOCX files</a>. While it does not specialize in merging, you can still effectively use it for basic merging tasks. This library is suitable for straightforward document manipulation and merging without the need for complex formatting preservation.</p>
<p><strong>Key Features:</strong></p>
<ol>
<li><p><strong>Basic Document Handling</strong> – Allows you to create, read, and edit DOCX files.</p>
</li>
<li><p><strong>Simple Merging</strong> – Can be used for basic merging tasks where advanced formatting is not a primary concern.</p>
</li>
<li><p><strong>Ease of Use</strong> – Provides a simple API for document manipulation, making it accessible for basic needs.</p>
</li>
<li><p><strong>Processing Time</strong> – This is the fastest method for merging documents, as it uses a simple, straightforward approach to combine documents. But it may not preserve complex formatting and styles.</p>
</li>
<li><p><strong>Memory Usage</strong> – This requires the least amount of memory usage among the three methods, as it only stores the merged document in memory temporarily before saving it to disk.</p>
</li>
</ol>
<h3 id="heading-python-docx-use-case"><code>python-docx</code> Use Case</h3>
<p>Use <code>python-docx</code> when:</p>
<ol>
<li><p>You need a simple solution for merging DOCX files without complex formatting requirements.</p>
</li>
<li><p>The documents you are merging do not include advanced elements like custom headers, footers, or styles.</p>
</li>
<li><p>You are looking for a straightforward approach to combine DOCX files with minimal setup.</p>
</li>
</ol>
<h3 id="heading-how-to-install-python-docx">How to Install <code>python-docx</code></h3>
<p>To use <code>python-docx</code>, install the library with:</p>
<pre><code class="lang-python">pip install python-docx
</code></pre>
<h3 id="heading-example-code-2">Example Code</h3>
<p>Here’s a Python script that uses <code>python-docx</code> to merge DOCX files:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> docx <span class="hljs-keyword">import</span> Document
<span class="hljs-keyword">import</span> os

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">merge_docs</span>(<span class="hljs-params">output_path, *input_paths</span>):</span>
    merged_doc = Document()

    <span class="hljs-keyword">for</span> file_path <span class="hljs-keyword">in</span> input_paths:
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isfile(file_path):
            print(<span class="hljs-string">f"File not found: <span class="hljs-subst">{file_path}</span>"</span>)
            <span class="hljs-keyword">continue</span>

        doc = Document(file_path)
        <span class="hljs-keyword">for</span> element <span class="hljs-keyword">in</span> doc.element.body:
            merged_doc.element.body.append(element)

    merged_doc.save(output_path)
    print(<span class="hljs-string">f"Documents merged successfully into <span class="hljs-subst">{output_path}</span>"</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    output_file = <span class="hljs-string">"merged_document.docx"</span>
    input_files = [<span class="hljs-string">"doc1.docx"</span>, <span class="hljs-string">"doc2.docx"</span>, <span class="hljs-string">"doc3.docx"</span>]
    merge_docs(output_file, *input_files)
</code></pre>
<p>In this code:</p>
<ol>
<li><p><code>Document</code> – Represents a Word document in Python.</p>
</li>
<li><p><code>element.body.append</code> – Appends the content of each document to the merged document.</p>
</li>
<li><p><code>save</code> – Saves the final merged document to the specified path.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Each method for merging Word documents in Python offers unique advantages depending on your specific needs:</p>
<ol>
<li><p><code>docxcompose</code> preserves complex formatting and styles, but may be slower for large documents and requires moderate memory usage.</p>
</li>
<li><p><code>pypandoc</code> is ideal for combining documents in different formats, but may lose some formatting and require less memory usage.</p>
</li>
<li><p><code>python-docx</code> is suitable for simple merging tasks with basic formatting needs, and is the fastest method with the least memory usage.</p>
</li>
</ol>
<p>When choosing a method, consider not only the complexity of your documents but also the performance and memory requirements of your application.</p>
<ul>
<li><p>If you need to merge large documents with complex formatting, <code>docxcompose</code> may be the best choice, but be prepared for slower processing times.</p>
</li>
<li><p>If you need to integrate content from various sources, <code>pypandoc</code> is a good option, but be aware of potential formatting losses.</p>
</li>
</ul>
<p>For simple merging tasks, <code>python-docx</code> is a fast and lightweight solution.</p>
<p>By considering the strengths and weaknesses of each method, including performance and memory considerations, you can make an informed decision and choose the best approach for your specific use case. This will ensure you experience an efficient and effective document merging processes.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Pandoc – An Open Source Tool for Technical Writers ]]>
                </title>
                <description>
                    <![CDATA[ Technical writers frequently navigate the complexities of various document formats and revisions. Pandoc, a free and open-source tool, offers a powerful solution to streamline these processes. In this tutorial, I'll explain the Pandoc's functionaliti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-pandoc/</link>
                <guid isPermaLink="false">66bb8ac7d2bda3e431549198</guid>
                
                    <category>
                        <![CDATA[ Google Docs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ markdown ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technical writing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 09 Jul 2024 15:33:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/pandoc-freecodecamp-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Technical writers frequently navigate the complexities of various document formats and revisions. <a target="_blank" href="https://pandoc.org/">Pandoc</a>, a free and open-source tool, offers a powerful solution to streamline these processes.</p>
<p>In this tutorial, I'll explain the Pandoc's functionalities, specifically focusing on two key areas that can significantly enhance the workflow for technical writers:</p>
<p><strong>Docs and Markdown Conversions</strong>: If you write in Google Docs to leverage their collaborative writing, editing, and review features, Pandoc empowers you to <a target="_blank" href="https://www.docstomarkdown.pro/convert-google-docs-to-markdown/">convert Google Docs into markdown</a> for publishing needs, and if you write in markdown, it helps you convert markdown to Google Docs or Microsoft Word for creating deliverables.</p>
<p><strong>Merging of Multiple Docs into One</strong>: If you work in the "content as component approach", Pandoc allows you to <a target="_blank" href="https://workspace.google.com/marketplace/app/merge_docs_pro/61337277026">merge multiple Google Docs into a single document</a> with a few commands for publishing needs.</p>
<p>You can also create scripts to automate these processes.</p>
<h2 id="heading-why-use-markdown-for-technical-writing">Why Use Markdown for Technical Writing?</h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/markdown-cheatsheet/">Markdown</a> is great for technical writers because it simplifies the writing process and improves collaboration. Here's why:</p>
<p><strong>Readability and Ease of Use</strong>: Markdown uses plain text symbols for formatting, making it clear and easy to learn. This lets you concentrate on writing clear content without getting caught up in styling complexities.</p>
<p><strong>Platform Independence</strong>: Markdown files are plain text, allowing you to write in any text editor on any device. This flexibility provides freedom in your writing environment and eliminates software compatibility concerns.</p>
<p><strong>Seamless Conversion with Free Tools</strong>: Free tools such as Pandoc offer format flexibility for markdown users, such as <a target="_blank" href="https://www.docstomarkdown.pro/convert-markdown-to-google-docs/">converting markdown to Google Docs</a>, Word documents, or HTML, ensuring compatibility with collaborative editing needs and final deliverables. This also extends to modern workflows, where large language models generate content in markdown. You can use ChatGPT or the Gemini API for creating initial drafts, integrate them with your writing, and then use Pandoc to convert the final document to Google Docs or Microsoft Word for team editing, feedback, and creating deliverables. This streamlined workflow empowers efficient and collaborative content creation.</p>
<p><strong>Version Control Friendly</strong>: Markdown's plain text nature enables seamless integration with version control systems like Git. This facilitates tracking changes, reverting to previous versions. This is particularly valuable for technical writing projects that often undergo revisions and involve multiple team members working on different sections.</p>
<h2 id="heading-why-merge-multiple-documents-into-one">Why Merge Multiple Documents into One?</h2>
<p>Technical writing often involves creating complex documents from smaller, reusable pieces. We call these pieces "content components." These components can be individual chapters, user guides, reference articles, or any other modular unit that contributes to the final product. In other words, content components are building blocks for bigger projects.</p>
<p>However, writing tools such as <a target="_blank" href="https://www.google.com/docs/about/">Google Docs</a> lack the ability to merge these components into a one document. This can be a major hurdle for projects like:</p>
<ol>
<li><strong>Technical Documentation:</strong> Building a user guide by assembling and reordering pre-written topics rather than crafting the entire document from scratch.</li>
<li><strong>Reference Guides:</strong> Consolidating multiple articles from a knowledge base into a single, printable reference manual.</li>
<li><strong>Book Authoring:</strong> Constructing a book by compiling individual chapters and appendices, streamlining the writing and editing process.</li>
</ol>
<p>In all these scenarios, the need to merge content components becomes crucial for creating well-structured and efficient documentation.</p>
<h2 id="heading-how-to-install-pandoc">How to Install Pandoc</h2>
<p>You can install Pandoc on your system using the packages available in the <a target="_blank" href="https://github.com/jgm/pandoc/releases">releases</a> list. The <a target="_blank" href="https://pandoc.org/installing.html">installation page</a> has a detailed tutorial on the steps to install it on different systems.</p>
<p>Once Pandoc is installed, you can use it in the command line to perform different document conversion operations as explained below.</p>
<h2 id="heading-how-to-convert-markdown-to-word-or-google-docs">How to Convert Markdown to Word or Google Docs</h2>
<p>To convert a markdown file to a Word document or Google Docs using Pandoc, follow these steps:</p>
<ol>
<li>Open a terminal or command prompt and navigate to the directory where your markdown file is located.</li>
<li>Run the following Pandoc command to convert your markdown file to a Word document:</li>
</ol>
<pre><code>pandoc input.md -o output.docx
</code></pre><p>Replace <code>input.md</code> with the name of your input markdown file, and <code>output.docx</code> with the desired name of your Word document.</p>
<p>To convert the Docx format into Google Docs, you can upload it to Google Drive and open it in Google Docs.</p>
<p>With these steps, you can convert your markdown files to Word documents or Google Docs using Pandoc.</p>
<h2 id="heading-how-to-convert-google-docs-or-word-to-markdown">How to Convert Google Docs or Word to Markdown</h2>
<p>In this section, I'll explain how to convert a Google Docs or Microsoft Word document into arkdown format.</p>
<p>While the Docs format is accepted by Pandoc, you cannot use the Google Docs URL directly with Pandoc. Therefore, you need to export the Google Doc into Docx format.</p>
<p>Go to <em>File</em> &gt; <em>Download</em> &gt; <em>Microsoft Word (.docx)</em> in your Google Doc to download the document in the <code>.docx</code> format as shown in the following image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Screenshot-2024-07-08-at-3.05.41-PM.png" alt="Image" width="600" height="400" loading="lazy">
<em>option to download document in .docx format</em></p>
<p>Now you'll have the Word document equivalent of the Google Docs.</p>
<p>To <a target="_blank" href="https://www.docstomarkdown.pro/convert-word-to-markdown/">convert the Word document to markdown</a> using Pandoc, run the following command in your terminal or command prompt:</p>
<pre><code>pandoc input.docx -o output.md
</code></pre><p>Replace <code>input.docx</code> with the name of your Word document, and <code>output.md</code> with the desired name of your markdown file.</p>
<h2 id="heading-how-to-merge-multiple-documents-into-one">How to Merge Multiple Documents into One</h2>
<p>To <a target="_blank" href="https://www.mergedocs.pro/">merge multiple Google Docs or Word documents into a single file</a> using Pandoc, you can follow these two steps:</p>
<ol>
<li>Convert individual documents to markdown using the Pandoc conversion command to convert each Google Doc or Word document into a separate markdown file (explained in the previous section).</li>
<li>Once you have individual markdown files, use the following Pandoc command to merge them into a single document.</li>
</ol>
<pre><code>pandoc file1.md file2.md -o merged_output.docx
</code></pre><p>Replace <code>file1.md</code> and <code>file2.md</code> with the names of your input markdown files. These files will be merged into one <code>merged_output.docx</code>.</p>
<p>You can use your desired output format instead of <code>merged_output.docx</code> based on your goals. For instance, you can create a single HTML file if you intend to publish it on the web, or use the markdown format if your publishing platform supports markdown.</p>
<p>This approach leverages Pandoc's strengths for format conversion and merging to achieve the desired outcome of a unified document.</p>
<p>For more information and helpful answers about using Pandoc, check out the <a target="_blank" href="https://pandoc.org/faqs.html">Pandoc FAQs</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, Pandoc is a powerful and versatile tool for technical writers, offering document conversion and merging capabilities. </p>
<p>With its ability to convert Google Docs into markdown and merge multiple documents into one, Pandoc streamlines the process of creating and publishing technical documentation.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Publish Google Docs to WordPress in an SEO-Optimized Way ]]>
                </title>
                <description>
                    <![CDATA[ WordPress is a popular content management system (CMS) known for its flexibility and user-friendly interface. But its built-in editor is not ideal for collaborative editing. Many publishers who work with writers need collaborative writing and editing... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/publish-google-docs-to-wordpress/</link>
                <guid isPermaLink="false">66bb8acb6b3bd8d6bf25ae4c</guid>
                
                    <category>
                        <![CDATA[ Google Docs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SEO ]]>
                    </category>
                
                    <category>
                        <![CDATA[ WordPress ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Mon, 26 Feb 2024 23:21:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/fcc-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>WordPress is a popular content management system (CMS) known for its flexibility and user-friendly interface. But its built-in editor is not ideal for collaborative editing.</p>
<p>Many publishers who work with writers need collaborative writing and editing features. This is where Google Docs comes into the picture. It’s a collaborative platform, enabling multiple users to write and edit simultaneously. </p>
<p>Google Docs also offers powerful formatting tools, simplifying the content creation process before transferring it to WordPress for publishing.</p>
<p>However, <a target="_blank" href="https://www.docstowp.pro/">converting Google Docs to WordPress</a> can add an extra step to your publishing workflow and requires some attention to detail.</p>
<p>This tutorial explores four seamless methods to bridge that gap and streamline your publishing journey:</p>
<ul>
<li>Manually converting using the copy-paste method</li>
<li>Publishing with SEO optimization using the <a target="_blank" href="https://workspace.google.com/marketplace/app/docs_to_wp_pro/346830534164">Docs to WP Pro</a> add-on</li>
<li>Using the WordPress Gutenberg editor </li>
<li>Using the Markdown conversion method</li>
</ul>
<h2 id="heading-using-the-simple-copy-paste-method">Using the Simple Copy Paste Method</h2>
<p>In this simple copy-paste approach, you can copy the contents from Google Docs and navigate to WordPress to create a new post, then paste in the content.</p>
<p>But when pasting content into WordPress, you may encounter some issues that require manual adjustments, especially if your WordPress site is using the Classic Editor.</p>
<p>First of all, you may have issues with spacing – for example, WordPress adds extra line breaks, as you can see in the image below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-145.png" alt="Image" width="600" height="400" loading="lazy">
<em>Unnecessary link breaks added by Wordpress</em></p>
<p>Second, you may have to remove or clean up messy code – WordPress adds unnecessary span tags to the content.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-144.png" alt="Image" width="600" height="400" loading="lazy">
<em>Unnecessary span tags</em></p>
<p>Finally, you may have to manually upload images to the Media library and include them in your posts, as it's not done automatically.</p>
<p>The spacing issues and the messy code can <a target="_blank" href="https://www.cloudflare.com/en-in/learning/performance/how-website-speed-boosts-seo/">affect your website performance</a>. HTML counts toward your overall page weight, so unnecessary code slows your page down, impacting both user experience and SEO. </p>
<p>Images also need to be manually compressed before uploading to the WordPress Media library.</p>
<p>Also, the native Google Docs doesn’t offer options for SEO optimization or the use of reusable blocks to add boilerplate content. So using this method requires more manual work for publishing from Google Docs to WordPress. </p>
<h2 id="heading-using-docs-to-wp-pro-add-on">Using Docs to WP Pro add-on</h2>
<p>The Google Docs add-on Docs to WP Pro can help you publish SEO-optimized posts from Google Docs to WordPress.</p>
<p><a href="https://workspace.google.com/marketplace/app/docs_to_wp_pro/346830534164?pann=b" target="_blank"><img src="https://workspace.google.com/static/img/marketplace/en/gwmBadge.svg?" alt="My image" width="417.14" height="68.57" loading="lazy"></a></p>
<p>The add-on allows you to configure the site once and includes additional capabilities, such as letting you create reusable blocks for content like <em>FAQs</em>, <em>Author bios</em>, and <em>affiliate disclaimers</em>. Beyond these, the add-on provides the following functionalities:</p>
<h3 id="heading-automated-internal-linking">Automated Internal Linking</h3>
<p>Adding <a target="_blank" href="https://ahrefs.com/seo/glossary/internal-link">internal links</a> to your article is crucial for enhancing user experience and SEO. After creating content, identifying potential keywords and adding relevant internal links is essential.</p>
<p>But manually managing this process can be challenging, especially with a large number of articles and multiple authors. It becomes difficult to identify all potentially related articles without a comprehensive overview of your site, leading to more guesswork.</p>
<p>The Docs to WP Pro add-on can automate internal linking by automatically identifying and linking relevant keywords within your content to related posts on your site. This saves you time and effort and can help improve the SEO of your content by creating relevant internal links.</p>
<h3 id="heading-related-posts-suggestions">Related Posts Suggestions</h3>
<p>Including a few related posts at the end of articles enhances reader engagement, increases <a target="_blank" href="https://www.semrush.com/blog/dwell-time/">dwell time</a>, and improves overall user experience.</p>
<p>For this use case, the tool suggests topics that can be added as <em>related posts</em>. These suggestions include additional contextual data for the target posts, such as <em>Relevance score</em>, <em>Number of incoming links</em>, <em>Post published on</em>, and <em>Post update on</em>.</p>
<p>This information helps you link to the most recent articles when you have multiple articles on closely related topics and ensures a balanced distribution of internal links.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-146.png" alt="Image" width="600" height="400" loading="lazy">
<em>Suggestions for Related posts</em></p>
<h3 id="heading-seo-optimization">SEO Optimization</h3>
<p>Apart from internal linking, the tool also supports other <a target="_blank" href="https://www.freecodecamp.org/news/wordpress-seo/">SEO optimizations</a> and seamlessly integrates with RankMath and Yoast.</p>
<p>The tool allows you to add a focus keyword and checks the content against it, suggesting optimizations such as the presence of the focus keyword in the title, subheadings, and image alt text. </p>
<p>The tool also evaluates whether the keyword is naturally integrated into the content or if it is overly used.</p>
<p>Additionally, the add-on provides useful information such as Flesch reading scores, content length, and reading time, helping you improve the readability of your content.</p>
<h3 id="heading-image-handling">Image Handling</h3>
<p>The add-on offers effortless image handling by automatically <a target="_blank" href="https://www.freecodecamp.org/news/image-optimization-558d9f449e3/">compressing images</a> before publishing to the WordPress media library. This ensures a sleek media library and enhances your site's loading time.</p>
<p>It also enables you to add featured images directly from Google Docs to your WordPress posts. It can also automatically generate Alt Text for your images, contributing to improved accessibility and SEO.</p>
<p>The add on has a free version with paid features. </p>
<h2 id="heading-using-the-wordpress-gutenberg-editor">Using the WordPress Gutenberg Editor</h2>
<p>Another option for publishing Google Docs to WordPress without additional add-ons is the WordPress Gutenberg editor. When you paste the Google Docs content into the <a target="_blank" href="https://www.wpbeginner.com/beginners-guide/how-to-use-the-new-wordpress-block-editor/">Gutenberg editor</a>, you won't encounter formatting issues such as extra line breaks or span tags.</p>
<p>This proves helpful when your content doesn't include images. But if your content contains images, the Gutenberg editor presents a few challenges. </p>
<p>After pasting the content into WordPress, checking the HTML code reveals that the image source is set to the location of the image in your Google Drive. This implies that you are hosting the images through your personal Google Drive, which is not recommended from a security standpoint.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-147.png" alt="Image" width="600" height="400" loading="lazy">
<em>Images hosted from your Google account</em></p>
<p>Also, deleting the image from your Google Drive or the Google Docs containing the image will result in the image disappearing from your website. This means you have to check your entire website and delete any links of images from your Google Drive.</p>
<p>An alternative approach is to upload the images manually to your WordPress media library and use those images in your posts. This adds some manual work and is error-prone. Also, the images must be manually compressed before uploading to the media library.</p>
<h2 id="heading-markdown-conversion-method">Markdown Conversion Method</h2>
<p>You can <a target="_blank" href="https://www.docstomarkdown.pro/">convert Google Docs to Markdown</a> format using the free and open source add on <a target="_blank" href="https://workspace.google.com/marketplace/app/docs_to_markdown/700168918607">Docs to Markdown</a>. The free tool will convert your fully formatted Google Doc to Markdown format (.md). You can paste this Markdown text into your WordPress editor for perfectly formatted text without any additional line breaks or span tags.</p>
<p>This option is also most useful <em>only</em> if your content doesn't include images. If your content does have images, it requires manual work to compress and upload your images into your WordPress media library and update the HTML accordingly.</p>
<p>Also, this method doesn't include built-in SEO features.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Transferring content from Google Docs to WordPress efficiently is essential for a smooth workflow. </p>
<p>This tutorial has presented four methods: manual copy-paste, using the Docs to WP Pro add-on, using WordPress Gutenberg editor and Markdown conversion method. </p>
<p>Each method has its own advantages and disadvantages, so the best choice for you will depend on your specific needs and preferences.</p>
<ul>
<li><strong>Manual copy-paste</strong> is a simple option but requires manual adjustments for formatting and images.</li>
<li><strong>Docs to WP Pro</strong> offers features like automated internal linking, SEO optimizations and image handling, but may require additional investment.</li>
<li><strong>WordPress Gutenberg editor</strong> is a best option for the text only posts, but if you have images, then it requires additional work to host your images on WordPress media library. </li>
<li><strong>Converting to Markdown</strong> preserves formatting but requires manual image handling and lacks SEO optimization features.</li>
</ul>
<p>Consider factors like the amount of content you create, your budget, and your technical expertise when making your decision.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Read a CSV File from S3 Bucket in AWS Lambda - A Definitive Guide ]]>
                </title>
                <description>
                    <![CDATA[ Amazon Simple Storage Service (S3) is a highly scalable, durable, and available object storage service. It is designed to store any amount of data, anytime, from anywhere on the web.  S3 is a key component of the Amazon Web Services (AWS) cloud platf... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/read-csv-file-from-s3-bucket-in-aws-lambda/</link>
                <guid isPermaLink="false">66bb8aced2bda3e43154919a</guid>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 12 Sep 2023 10:44:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/unnamed.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Amazon Simple Storage Service (S3) is a highly scalable, durable, and available object storage service.</p>
<p>It is designed to store any amount of data, anytime, from anywhere on the web. </p>
<p>S3 is a key component of the Amazon Web Services (AWS) cloud platform.</p>
<p>AWS Lambda is a serverless computing service that lets you run code without provisioning or managing servers. </p>
<p>Lambda executes your code only when needed and scales automatically, from a few requests per day to thousands per second. </p>
<p>You are billed only for the compute time you consume – there is no charge when your code is not running.</p>
<p>S3 and Lambda are two of the most popular AWS services. They can be used together to create robust, scalable, cost-effective applications. </p>
<p>S3 can be used to store data that is processed by Lambda functions. </p>
<p>Lambda's event-driven architecture seamlessly interfaces with S3 events, allowing developers to effortlessly trigger serverless functions in response to changes within S3 buckets. This allows you to build applications that automatically process data as it is added to S3.</p>
<p>This tutorial will teach you how to read a CSV file from an S3 bucket in AWS Lambda using the <code>requests</code> library or the <code>boto3</code> library.</p>
<h2 id="heading-how-to-create-a-lambda-execution-role-with-s3-read-permissions">How to Create a Lambda Execution Role with S3 Read permissions</h2>
<p>For the Lambda service to read the files from the S3 bucket, you need to create a lambda execution role that has S3 read permissions. </p>
<p>To create a lambda execution role:</p>
<ol>
<li>Sign in to the AWS Console and navigate to the Identity and Access Management (IAM) console</li>
<li>Click Roles and then click Create role:</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-52.png" alt="Image" width="600" height="400" loading="lazy">
<em>Create Role</em></p>
<ol start="3">
<li>Choose AWS service as a Trusted Entity and Lambda as the Use Case as shown in the following image:</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-54.png" alt="Image" width="600" height="400" loading="lazy">
<em>Select Trusted Entity and Use case</em></p>
<ol start="4">
<li>Add the AmazonS3ReadOnlyAccess policy for read-only S3 access:</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-56.png" alt="Image" width="600" height="400" loading="lazy">
<em>Adding permissions</em></p>
<ol start="5">
<li>Give the role a name and description and review the attached policies. Finally, click Create role to create the IAM role as shown in the following image:</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-58.png" alt="Image" width="600" height="400" loading="lazy">
<em>Creating Role</em></p>
<p>To Attach Role to the Lambda Function:</p>
<ol>
<li>Go to your Lambda function in the Lambda console if it is already existing, or create a Lambda function if you need to create a new one</li>
<li>In the Execution role section, click Edit</li>
<li>Choose the IAM role you created</li>
<li>Save to attach the role to your Lambda function:</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-59.png" alt="Image" width="600" height="400" loading="lazy">
<em>Attaching the Role to the Lambda Function</em></p>
<p>Now, let's see how to read a CSV file.</p>
<h2 id="heading-how-to-read-a-csv-file-from-s3-bucket-using-the-requests-library-in-aws-lambda">How to Read a CSV File from S3 Bucket Using the Requests Library in AWS Lambda</h2>
<p>The Requests library is a popular Python module for making HTTP requests and interacting with web services. </p>
<p>It simplifies the process of sending HTTP requests, handling responses, and managing various aspects of web communication.</p>
<p>With an easy-to-use and intuitive API, Requests allows developers to send <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, and other HTTP requests with minimal code. This makes it a valuable tool for tasks such as fetching web data, interacting with RESTful APIs, and more. </p>
<p>You can use the requests library to send a <code>GET</code> request and read a CSV file from S3 bucket. </p>
<p>Once the <code>GET</code> request is complete, you'll receive a response with appropriate response codes. </p>
<p>If the get request is successful, it will return the status code <code>200</code>. You can get the data from <code>response.text</code>. </p>
<p>The following code demonstrates how to send the <code>GET</code> request and read the response:</p>
<pre><code class="lang-python">response = requests.get(url)

<span class="hljs-keyword">if</span> response.status_code == <span class="hljs-number">200</span>:
    <span class="hljs-comment"># Parse the CSV data from the response content</span>
    csv_data = response.text
</code></pre>
<p>Next, use the <code>CSV</code> reader to read the CSV content from <code>csv_data</code> and iterate over the reader object to access each row of the CSV file: </p>
<pre><code class="lang-python">    reader = csv.reader(csv_data.splitlines())

    <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> reader:

        print(row)
</code></pre>
<p>The following code demonstrates the complete program to get the CSV file from S3 using the requests library: </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests

<span class="hljs-keyword">import</span> csv

<span class="hljs-comment"># URL of the CSV file</span>
url = <span class="hljs-string">"https://mrcloudgurudemo.s3.us-east-2.amazonaws.com/sample_csv.csv"</span>

<span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># Send an HTTP GET request to the URL</span>
    response = requests.get(url)

    <span class="hljs-comment"># Check if the request was successful (HTTP status code 200)</span>
    <span class="hljs-keyword">if</span> response.status_code == <span class="hljs-number">200</span>:
        <span class="hljs-comment"># Parse the CSV data from the response content</span>
        csv_data = response.text

        <span class="hljs-comment"># You can now process the CSV data as needed</span>
        <span class="hljs-comment"># For example, you can use the csv.reader to read the data</span>
        reader = csv.reader(csv_data.splitlines())

        <span class="hljs-comment"># Iterate through the rows in the CSV</span>
        <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> reader:
            <span class="hljs-comment"># Process each row as needed</span>
            print(row)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"Failed to fetch data. Status code: <span class="hljs-subst">{response.status_code}</span>"</span>)

<span class="hljs-keyword">except</span> requests.exceptions.RequestException <span class="hljs-keyword">as</span> e:
    print(<span class="hljs-string">f"Error: <span class="hljs-subst">{e}</span>"</span>)
</code></pre>
<p>Output:</p>
<pre><code>    [<span class="hljs-string">'sepal_length'</span>, <span class="hljs-string">'sepal_width'</span>, <span class="hljs-string">'petal_length'</span>, <span class="hljs-string">'petal_width'</span>, <span class="hljs-string">'species'</span>]
    [<span class="hljs-string">'5.1'</span>, <span class="hljs-string">'3.5'</span>, <span class="hljs-string">'1.4'</span>, <span class="hljs-string">'0.2'</span>, <span class="hljs-string">'Iris-setosa'</span>]
    [<span class="hljs-string">'4.9'</span>, <span class="hljs-string">'3'</span>, <span class="hljs-string">'1.4'</span>, <span class="hljs-string">'0.2'</span>, <span class="hljs-string">'Iris-setosa'</span>]
    [<span class="hljs-string">'4.7'</span>, <span class="hljs-string">'3.2'</span>, <span class="hljs-string">'1.3'</span>, <span class="hljs-string">'0.2'</span>, <span class="hljs-string">'Iris-setosa'</span>]
    [<span class="hljs-string">'4.6'</span>, <span class="hljs-string">'3.1'</span>, <span class="hljs-string">'1.5'</span>, <span class="hljs-string">'0.2'</span>, <span class="hljs-string">'Iris-setosa'</span>]
    [<span class="hljs-string">'5'</span>, <span class="hljs-string">'3.6'</span>, <span class="hljs-string">'1.4'</span>, <span class="hljs-string">'0.2'</span>, <span class="hljs-string">'Iris-setosa'</span>]
</code></pre><p>Note that if you’re using the <code>requests</code> library version 2.30.0 in AWS lambda, you might get a <a target="_blank" href="https://www.mrcloud.guru/solve-error-cannot-import-name-default-ciphers-from-urllib3-util-ssl-aws-lambda/">Cannot Import Name DEFAULT<em>CIPHERS from urllib3.util.ssl</em></a> error when any of the dependent libraries try to import the <code>default_ciphers</code> variable from <code>urllib3</code>. </p>
<p>You can solve this error by downgrading the requests library to 2.29.0.</p>
<h2 id="heading-how-to-read-a-csv-file-using-the-boto3-client-getobject-method-in-aws-lambda">How to Read a CSV File Using the Boto3 Client <code>get_Object()</code> Method in AWS Lambda</h2>
<p>The second option to read a CSV file is using the <a target="_blank" href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a> library.</p>
<p>Boto3 is the AWS SDK for Python. It provides an object-oriented API as well as low-level access to AWS services. </p>
<p>Boto3 makes it easy to create, configure, and manage AWS resources from your Python applications. </p>
<p>For example, you can <a target="_blank" href="https://www.mrcloud.guru/reading-file-content-from-aws-s3-bucket-using-boto3/">read the content of a file from an S3 bucket</a> programmatically.</p>
<p>Note that in order  to interact with the AWS service using Boto3, you must <a target="_blank" href="https://www.mrcloud.guru/fix-the-boto3-nocredentialserror-unable-to-locate-credentials-error/">configure the security credentials to avoid the unable to locate credentials error</a>. </p>
<p>You can configure the security credentials using the <code>aws configure</code> command.</p>
<p>To read a CSV File Using the Boto3 Client <a target="_blank" href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/get_object.html">get_Object()</a> Method in AWS Lambda first create the Boto3 client:</p>
<pre><code>s3 = boto3.client(<span class="hljs-string">'s3'</span>)
</code></pre><p>Next, invoke the <code>get_object()</code> method from the Boto3 client and pass the bucket name and the object name:</p>
<pre><code>response = s3.get_object(Bucket=bucket_name, Key=file_key)
</code></pre><p>Now, read the response body using <code>response['Body'].read()</code>:</p>
<pre><code>csv_content = response[<span class="hljs-string">'Body'</span>].read().decode(<span class="hljs-string">'utf-8'</span>)
</code></pre><p>Use the Pandas library <a target="_blank" href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html"><code>read_csv()</code></a> method to parse the response text as CSV content and create a pandas dataframe out of it. You can also print the first five lines to see if the data is successfully read:</p>
<pre><code>df = pd.read_csv(io.StringIO(csv_content))
print(df.head(<span class="hljs-number">5</span>))
</code></pre><p>The following code demonstrates the complete program to read a CSV file from S3 bucket using Boto3:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3

<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

<span class="hljs-keyword">import</span> io

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">lambda_handler</span>(<span class="hljs-params">event, context</span>):</span>
    <span class="hljs-comment"># Initialize the S3 client</span>
    s3 = boto3.client(<span class="hljs-string">'s3'</span>)

    <span class="hljs-comment"># Specify the S3 bucket and object key of the CSV file</span>
    bucket_name = <span class="hljs-string">'mrcloudgurudemo'</span>
    file_key = <span class="hljs-string">'sample_csv.csv'</span>

    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Read the CSV file from S3</span>
        response = s3.get_object(Bucket=bucket_name, Key=file_key)
        csv_content = response[<span class="hljs-string">'Body'</span>].read().decode(<span class="hljs-string">'utf-8'</span>)

        <span class="hljs-comment"># Create a Pandas DataFrame</span>
        df = pd.read_csv(io.StringIO(csv_content))

        <span class="hljs-comment"># Now you have your DataFrame (df) for further processing</span>
        <span class="hljs-comment"># Example: Print the first 5 rows</span>
        print(df.head(<span class="hljs-number">5</span>))

        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">'statusCode'</span>: <span class="hljs-number">200</span>,
            <span class="hljs-string">'body'</span>: <span class="hljs-string">'File read successfully into DataFrame.'</span>
        }

    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">'statusCode'</span>: <span class="hljs-number">500</span>,
            <span class="hljs-string">'body'</span>: str(e)
        }
</code></pre>
<p>Output:</p>
<pre><code>sepal_length  sepal_width  petal_length  petal_width      species
<span class="hljs-number">0</span>           <span class="hljs-number">5.1</span>          <span class="hljs-number">3.5</span>           <span class="hljs-number">1.4</span>          <span class="hljs-number">0.2</span>  Iris-setosa
<span class="hljs-number">1</span>           <span class="hljs-number">4.9</span>          <span class="hljs-number">3.0</span>           <span class="hljs-number">1.4</span>          <span class="hljs-number">0.2</span>  Iris-setosa
<span class="hljs-number">2</span>           <span class="hljs-number">4.7</span>          <span class="hljs-number">3.2</span>           <span class="hljs-number">1.3</span>          <span class="hljs-number">0.2</span>  Iris-setosa
<span class="hljs-number">3</span>           <span class="hljs-number">4.6</span>          <span class="hljs-number">3.1</span>           <span class="hljs-number">1.5</span>          <span class="hljs-number">0.2</span>  Iris-setosa
<span class="hljs-number">4</span>           <span class="hljs-number">5.0</span>          <span class="hljs-number">3.6</span>           <span class="hljs-number">1.4</span>          <span class="hljs-number">0.2</span>  Iris-setosa
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned two methods for reading a CSV file from an S3 bucket in AWS Lambda: using the <code>requests</code> library and the <code>Boto3</code> library. </p>
<p>Both methods are effective and have their own advantages. The requests library is a simple and lightweight library that is easy to use. </p>
<p>Boto3 is the official AWS SDK for Python and provides a more comprehensive set of features and functionality.</p>
<p>Ultimately, the best method for reading a CSV file from S3 in AWS Lambda depends on your specific needs. </p>
<p>If you need a simple and easy-to-use solution, the <code>requests</code> library is a good choice. </p>
<p>If you need a more comprehensive and feature-rich solution, then <code>Boto3</code> is a better choice.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Save a Base64 String as a PDF File on the Client Side in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Base64 strings represent binary objects in textual format. They are designed to transmit binary data between channels that only support a textual format. Sometimes, you might receive PDF files from various services as a Base64 string, and you may nee... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/save-a-base64-string-as-pdf-on-client-side-in-javascript/</link>
                <guid isPermaLink="false">66bb8ad15d242388375d386c</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Mon, 27 Feb 2023 18:20:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/How-to-check-if-a-String-is-URL-in-Javascript.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Base64 strings represent binary objects in textual format. They are designed to transmit binary data between channels that only support a textual format.</p>
<p>Sometimes, you might receive PDF files from various services as a Base64 string, and you may need to convert them to a PDF file on the client side after receiving the response.</p>
<p>This tutorial teaches you how to save a Base64 string as a PDF on the client side in JavaScript.</p>
<h2 id="heading-base64-string-format">Base64 String Format</h2>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs">Base64 strings</a> are in text format, and they have a metadata prefix on them.</p>
<p><strong>Here's the syntax:</strong></p>
<pre><code>data:[&lt;mediatype&gt;][;base64],&lt;data&gt;
</code></pre><p>Where,</p>
<ul>
<li><code>data</code> is a common prefix</li>
<li><code>Mediatype</code> is a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">Mimetype</a> string that represents the type of the file</li>
<li><code>Base64</code> shows that the string is a Base64 string</li>
</ul>
<p>Let's look at an example:</p>
<pre><code>data:application/pdf;base64,<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Base64</span> <span class="hljs-attr">String</span>&gt;</span></span>
</code></pre><p>The above string represents a Base64 string of a PDF file.</p>
<p>Base64 strings are also known as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs">DataURLs</a>. Data URLs are URLs that are prefixed with the <code>data:</code> scheme to allow users to embed files inline in the <code>HTML</code> document.</p>
<p>To convert a PDF file into a Base64 string, you can use the <a target="_blank" href="https://www.base64encode.pro/">online Base64 Encoder tool</a>. You can upload the file and click <em>Encode</em>. It’ll return a text file that contains the base64 equivalent string of the PDF file.</p>
<p>Now let's use the output string and <a target="_blank" href="https://www.base64decode.pro/blog/how-to-convert-a-base64-string-to-a-file-in-java-with-examples/">convert the Base64 string into a PDF file</a> format on the client side using JavaScript.</p>
<h2 id="heading-how-to-create-a-user-interface-with-html">How to Create a User Interface with HTML</h2>
<p>For this demonstration, let's create a simple UI in HTML. Our UI will have:</p>
<ul>
<li>A <code>text area</code> that accepts a Base64 string in the text box</li>
<li>A <code>Button</code>, with a click event, that converts the Base64 string available in the text area into a PDF format and downloads it automatically.</li>
</ul>
<p>Here's the code to do that:</p>
<pre><code>&lt;label <span class="hljs-keyword">for</span>=<span class="hljs-string">"Base64StringTxtBox"</span>&gt;Base64 <span class="hljs-built_in">String</span>&lt;/label&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"Base64StringTxtBox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"Base64Text"</span> <span class="hljs-attr">rows</span>=<span class="hljs-string">"4"</span> <span class="hljs-attr">cols</span>=<span class="hljs-string">"50"</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">textarea</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"Convert"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"downloadAsPDF()"</span>&gt;</span>Convert to PDF<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
</code></pre><h2 id="heading-how-to-use-the-anchor-tag">How to Use the Anchor Tag</h2>
<p>To convert the Base64 string into a PDF file, you'll need to do the following:</p>
<ul>
<li>Get the Base64 string from the Textarea</li>
<li>Create an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a">Anchor</a> element in the HTML element</li>
<li>Assign the Base64 string to the <code>href</code> attribute of the anchor element</li>
<li>Assign a filename to the <code>download</code> attribute. The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download">download</a> instructs the browser to treat the linked URL as a download option. When the anchor link is clicked, the target specified in the <code>href</code> attribute is downloaded with the filename.</li>
</ul>
<p>Let's look at an example:</p>
<p>The following JavaScript code downloads the Base64 string as a PDF file:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">downloadAsPDF</span>(<span class="hljs-params">pdf</span>) </span>{

  <span class="hljs-keyword">var</span> base64String = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"Base64StringTxtBox"</span>).value;

  <span class="hljs-keyword">const</span> downloadLink = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"a"</span>);

  downloadLink.href = base64String;

  downloadLink.download = <span class="hljs-string">"convertedPDFFile.pdf"</span>;

  downloadLink.click();
}
</code></pre><h2 id="heading-how-to-handle-base64-strings-without-metadata">How to Handle Base64 Strings without Metadata</h2>
<p>In some cases, a base64 strings might not have a metadata prefix. The user might receive just the Base64 data as a response.</p>
<p>Each file type has a common prefix in the Base64 string. For example,</p>
<ul>
<li>A JPG file Base64 string starts with <code>/9j</code></li>
<li>A PDF file Base64 string starts with  <code>JVB</code></li>
<li>A PNG file Base64 string starts with <code>iVB</code></li>
</ul>
<p>The Stackoverflow answer <a target="_blank" href="https://stackoverflow.com/a/58158656/8510024">here</a> explains more in detail about finding the Mime type from the Base64 string without metadata.</p>
<p>Now let's learn how to download Base64 string without metadata as a PDF file.</p>
<ul>
<li>Check if the Base64 starts with <code>JVB</code>, append the metadata <code>data:application/pdf;base64,</code> to the existing Base64 string, and download it using the anchor tag.</li>
<li>Check if the Base64 string starts with the <code>Data:</code> prefix. If yes, directly download the file using the anchor tag.</li>
<li>If the string doesn’t have the prefix <code>data:</code> or <code>JVB</code>, then it is not a valid PDF file Base64 string. Alert the user with an appropriate error message.</li>
</ul>
<p>Let's look at an example.</p>
<p>The following code demonstrates how to validate the Base64 string before downloading it as a PDF file.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">downloadAsPDF</span>(<span class="hljs-params">pdf</span>) </span>{

  <span class="hljs-keyword">var</span> base64String = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"Base64StringTxtBox"</span>).value;

  <span class="hljs-keyword">if</span> (base64String.startsWith(<span class="hljs-string">"JVB"</span>)) {
    base64String = <span class="hljs-string">"data:application/pdf;base64,"</span> + base64String;
    downloadFileObject(base64String);
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (base64String.startsWith(<span class="hljs-string">"data:application/pdf;base64"</span>)) {
    downloadFileObject(base64String);
  } <span class="hljs-keyword">else</span> {
    alert(<span class="hljs-string">"Not a valid Base64 PDF string. Please check"</span>);
  }

}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">downloadFileObject</span>(<span class="hljs-params">base64String</span>) </span>{
  <span class="hljs-keyword">const</span> linkSource = base64String;
  <span class="hljs-keyword">const</span> downloadLink = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"a"</span>);
  <span class="hljs-keyword">const</span> fileName = <span class="hljs-string">"convertedPDFFile.pdf"</span>;
  downloadLink.href = linkSource;
  downloadLink.download = fileName;
  downloadLink.click();
}
</code></pre><h2 id="heading-how-to-use-the-online-base64-decode-tool">How to Use the Online Base64 Decode Tool</h2>
<p>You can also use the <a target="_blank" href="https://www.base64decode.pro/">Online Base64 Decode tool</a> to convert the Base64 String into a PDF file. You can add the Base64 string in a text file and upload it to the online tool. It’ll convert the file and download it.</p>
<h3 id="heading-jsfiddle-link">JSfiddle Link</h3>
<p>The above two tutorials are available in the following JSfiddle links:</p>
<ul>
<li>Example 1 – <a target="_blank" href="https://jsfiddle.net/jsowl/yxbts6ap/4/">Download the Base64 string with the Meta Data prefix</a></li>
<li>Example 2 – <a target="_blank" href="https://jsfiddle.net/jsowl/vmu5t80b/9/">Download the Base64 string without the Meta Data prefix</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>To summarise, in this tutorial you have learned what Base64 strings are, how to convert a Base64 string to a file, and then download it on the client side using JavaScript. </p>
<p>You’ve also learned about the Metadata prefixes of the Base64 strings.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Remove a Key from a Dictionary While Iterating Over it ]]>
                </title>
                <description>
                    <![CDATA[ Python dictionaries allow you to store values in a Key and Value format. You can access the values using the key. You can also iterate through the complete dictionary to access every element. Sometimes while iterating through the dictionary, you may ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-remove-a-key-from-the-dictionary-while-iterating-over-it-definitive-guide/</link>
                <guid isPermaLink="false">66bb8ac46b3bd8d6bf25ae4a</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Wed, 06 Jul 2022 21:56:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Freecodecamp_dictionary_delete_iterate.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python dictionaries allow you to store values in a <code>Key</code> and <code>Value</code> format.</p>
<p>You can access the values using the key. You can also iterate through the complete dictionary to access every element.</p>
<p>Sometimes while iterating through the dictionary, you may need to remove a key from the dictionary.</p>
<p>This tutorial will teach you how to remove a key from a dictionary <strong>while iterating over it</strong>.</p>
<p>To remove a key directly without iterating, read the freeCodeCamp tutorial <a target="_blank" href="https://www.freecodecamp.org/news/how-to-remove-a-key-from-a-python-dictionary-delete-key-from-dict/">How to Remove a key from a Python Dictionary</a>.</p>
<h2 id="heading-how-to-create-a-dictionary">How to Create a Dictionary</h2>
<p>Let's first create a dictionary with some key-value pairs using the assignment operator.</p>
<p>To add a key to the dictionary using different methods, read <a target="_blank" href="https://www.stackvidhya.com/python-add-key-to-dictionary/">How to Add a Key to a Dictionary</a></p>
<p>After creating the dictionary, you can use the <code>for</code> loop to iterate through it and print the values to check if the dictionary has been created successfully.</p>
<p><strong>Here's the code:</strong></p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> yourdict.keys():
    print(key, yourdict[key])
</code></pre>
<p>You can print the values in the dictionary as follows.</p>
<p><strong>Output:</strong></p>
<pre><code>    one <span class="hljs-number">1</span>
    two <span class="hljs-number">2</span>
    three <span class="hljs-number">3</span>
    four <span class="hljs-number">4</span>
</code></pre><p>To check if a key exists in a dictionary without iterating over it, read <a target="_blank" href="https://www.stackvidhya.com/check-if-key-exists-in-dictionary-python/">how to check if a key exists in dictionary in Python</a>.</p>
<h2 id="heading-how-to-check-the-python-version">How to Check the Python Version</h2>
<p>Python 2 and Python 3 work <em>differently</em> when you try to delete a key from a dictionary while iterating.</p>
<p>To check which version of Python you are using, use the below code snippet.</p>
<p><strong>Here's the code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
print(sys.version)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code><span class="hljs-number">3.8</span><span class="hljs-number">.2</span> (<span class="hljs-keyword">default</span>, Sep  <span class="hljs-number">4</span> <span class="hljs-number">2020</span>, <span class="hljs-number">00</span>:<span class="hljs-number">03</span>:<span class="hljs-number">40</span>) [MSC v<span class="hljs-number">.1916</span> <span class="hljs-number">32</span> bit (Intel)]
</code></pre><p>You'll see whatever version you have. And now you know which version of Python you are using.</p>
<p>You can follow the appropriate methods explained below.</p>
<h2 id="heading-how-to-delete-a-key-from-a-dict-based-on-key-value-python-3">How to Delete A Key from a Dict Based on Key Value – Python 3</h2>
<p>This section teaches you how to delete a key from a dictionary using Python 3.</p>
<p>You need to convert the <code>keys</code> to a <code>list</code> using the <code>list(dict.keys())</code> and <a target="_blank" href="https://www.stackvidhya.com/iterate-through-dictionary-python/">iterate through a dictionary</a> using the <code>for</code> loop.  </p>
<p>While converting the <code>keys</code> to a <code>list</code>, Python 3 creates a <em>new copy</em> of the keys in the list. There will be no reference to the dictionary during the iteration.</p>
<p>If you do not convert it into a list, then the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#dict.keys">keys</a> method just returns a new view of the keys with reference to the currently iterated dictionary.</p>
<p>Now, during each iteration of the list of keys, you can check if the <code>key</code> is <em>equal to the item</em> you need to <em>delete.</em> If it is <code>True</code>, you can delete the <code>key</code> using the <code>del</code> statement.</p>
<p><strong>Here's the code:</strong></p>
<p>The below code demonstrates how to remove a key from the dictionary while iterating over it using Python 3.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> list(yourdict.keys()):
    <span class="hljs-keyword">if</span> k == <span class="hljs-string">"four"</span>:
        <span class="hljs-keyword">del</span> yourdict[k]

yourdict
</code></pre>
<p>As you can see in the code below, the key <em>four</em> gets deleted from the dictionary while iterating through it.</p>
<p><strong>Output:</strong></p>
<pre><code>    {<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
</code></pre><p>If you use the <code>dict.keys()</code> method to iterate and issue a <code>del</code> statement, you’ll see the below error in Python 3.</p>
<pre><code class="lang-python">RuntimeError: dictionary changed size during iteration
</code></pre>
<h2 id="heading-how-to-delete-a-key-from-a-dict-based-on-values-python-3">How to Delete a Key from a Dict Based on Values – Python 3</h2>
<p>This section teaches you how to remove a key from a dictionary based on the value of the key while iterating over the dictionary.</p>
<p>First, you need to convert the dictionary keys to a <code>list</code> using the <code>list(dict.keys())</code> method.</p>
<p>During each iteration, you can check if the <em>value of a key</em> is equal to the desired value. If it is <code>True</code>, you can issue the <code>del</code> statement to delete the key.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> list(yourdict.keys()):
    <span class="hljs-keyword">if</span> yourdict [k] == <span class="hljs-number">4</span>:
        <span class="hljs-keyword">del</span> yourdict[k]

print(yourdict)
</code></pre>
<p>The key <em>four</em> gets deleted based on its value <em>4</em>.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">{‘three’: <span class="hljs-number">3</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>}
</code></pre>
<h2 id="heading-how-to-delete-a-key-from-a-dict-based-on-the-key-python-2">How to Delete a Key from a Dict Based on the Key – Python 2</h2>
<p>This section teaches you how to remove a key from a dictionary while iterating over it using Python 2.</p>
<p>You can directly <a target="_blank" href="https://www.stackvidhya.com/iterate-through-dictionary-python/">iterate through a dictionary</a> using the <code>dict.keys()</code> method. In Python 2, the <code>dict.keys()</code> method creates a copy of the keys and iterates over the <code>copy</code> instead of iterating through the keys directly. So there will be <em>no reference</em> to the dictionary directly while iterating.</p>
<p>Now during each iteration, you can check if the item is <em>equal to the key</em> you want to delete. And if it is equal, you can issue the <code>del</code> statement. It’ll remove the key from the dictionary.</p>
<p><strong>Here's the code:</strong></p>
<p>The below code demonstrates how to remove a key from dictionary while iterating over it using Python 2.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> yourdict.keys():
    <span class="hljs-keyword">if</span> k == <span class="hljs-string">"four"</span>:
        <span class="hljs-keyword">del</span> yourdict[k]

yourdict
</code></pre>
<p>The key <em>four</em> gets deleted, and only the other items are available in the dictionary.</p>
<p><strong>Output:</strong></p>
<pre><code>    {<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
</code></pre><p>This is how you can remove a key based on the key.</p>
<h2 id="heading-how-to-delete-a-key-in-a-dict-based-on-values-python-2">How to Delete a Key in a Dict Based on Values – Python 2</h2>
<p>This section teaches you how to remove a key from a dictionary based on the value of the key while iterating over the dictionary.</p>
<p>Iterate over the dictionary using the <code>dict.items()</code> method. It’ll return the key-value pair during each iteration.</p>
<p>Then you can check if the <code>value</code> of the current iteration <em>equals your desired value</em> to be removed. Then issue the <code>del</code> statement to remove the key from the dictionary.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> key, val <span class="hljs-keyword">in</span> yourdict.items():
    <span class="hljs-keyword">if</span> val == <span class="hljs-number">3</span>:
        <span class="hljs-keyword">del</span> yourdict[key]

print(yourdict)
</code></pre>
<p>The key <em>three</em> gets deleted based on its value <em>3</em>. All other items are available in the dictionary.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">{<span class="hljs-string">'four'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>}
</code></pre>
<h2 id="heading-why-do-python-3-and-python-2-work-differently">Why Do Python 3 and Python 2 Work Differently?</h2>
<p>When using the <code>dict.keys()</code> method, Python 3 returns a <em>view</em> of the keys. This means there is a reference to the dictionary while iterating over it. </p>
<p>On the other hand, Python 2 returns a <em>copy</em> of the keys, meaning there is NO dictionary reference while iterating it. This means that deletion will be successful without problems.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you’ve learned how to remove a key from a dictionary while iterating over it in different versions of Python – Python 2 and Python 3.</p>
<p>You’ve also learned how to delete a key based on a key or the value of a key.</p>
<p>If you liked this article, feel free to share it.</p>
<p>You can check out my other <a target="_blank" href="https://www.stackvidhya.com">Python tutorials here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Check if a JavaScript String is a Valid URL ]]>
                </title>
                <description>
                    <![CDATA[ A URL – or Uniform Resource Locator – is text used to identify resources like web pages, images, and videos on the internet. We commonly refer to URLs as website addresses, and they're used for file transfer, emails, and other applications. URLs cons... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/check-if-a-javascript-string-is-a-url/</link>
                <guid isPermaLink="false">66bb8abdd2bda3e431549196</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Fri, 24 Jun 2022 15:09:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/freecodecamp_new.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A URL – or Uniform Resource Locator – is text used to identify resources like web pages, images, and videos on the internet.</p>
<p>We commonly refer to URLs as website addresses, and they're used for file transfer, emails, and other applications.</p>
<p>URLs consist of multiple parts – protocol, domain name, and so on – that tell the browser how and where to retrieve the resource.</p>
<p>In JavaScript, you may need to use a URL in the anchor tags or buttons to link the user to another webpage. This URL string must be verified to make sure it's a valid URL in such situations.</p>
<p>This tutorial will teach you some ways to check if a JavaScript string is a valid URL.</p>
<p>To learn how to get the current URL in JavaScript, you can read this article on <a target="_blank" href="https://www.jsowl.com/how-to-get-the-current-url-in-javascript/">How to Get the Current URL in JavaScript</a>.</p>
<h2 id="heading-how-to-check-if-a-string-is-a-valid-url-using-regex">How to Check if a String is a Valid URL Using Regex</h2>
<p>Regular expressions (regex) are patterns that match character combinations in a JavaScript string. In JavaScript, <a target="_blank" href="https://www.freecodecamp.org/news/a-quick-and-simple-guide-to-javascript-regular-expressions-48b46a68df29/">regular expressions</a> are also known as objects that provide different methods to perform various operations.</p>
<p>You can construct a regular expression in two ways:</p>
<ul>
<li>Using regular expression literals</li>
<li>Using regular expression constructors</li>
</ul>
<p><strong>Note:</strong> It is appropriate to use the regular expression method when you just want to check if a string is a valid URL and don't want any other additional objects created.</p>
<p>Let's learn how these two methods work.</p>
<h3 id="heading-how-to-use-regular-expression-literals">How to use regular expression literals</h3>
<p>In a regular expression literal, the pattern is enclosed between the slashes, as you'll see below.</p>
<p>The pattern includes the validation of parts needed in the <code>URL</code>. For example, a protocol, <code>https</code>, a <code>//</code>, and so on.</p>
<pre><code><span class="hljs-keyword">const</span> urlPattern = <span class="hljs-regexp">/(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&amp;%!\-\/]))?/</span>;
</code></pre><h3 id="heading-how-to-use-a-regular-expression-constructor">How to use a regular expression constructor</h3>
<p>To create a regular expression using the construction method, use the <code>RegExp()</code> constructor and pass the pattern as a parameter.</p>
<pre><code><span class="hljs-keyword">const</span> urlPattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&amp;%!\-\/]))?'</span>);
</code></pre><p>To demonstrate how to validate if a string is a <code>URL</code>, let's create a method that will validate a JavaScript <code>String</code> using the regular expression constructor and return <code>True</code> or <code>False</code> based on the matched pattern.</p>
<pre><code class="lang-js">    <span class="hljs-keyword">const</span> isValidUrl = <span class="hljs-function"><span class="hljs-params">urlString</span>=&gt;</span> {
          <span class="hljs-keyword">var</span> urlPattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'^(https?:\\/\\/)?'</span>+ <span class="hljs-comment">// validate protocol</span>
        <span class="hljs-string">'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'</span>+ <span class="hljs-comment">// validate domain name</span>
        <span class="hljs-string">'((\\d{1,3}\\.){3}\\d{1,3}))'</span>+ <span class="hljs-comment">// validate OR ip (v4) address</span>
        <span class="hljs-string">'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'</span>+ <span class="hljs-comment">// validate port and path</span>
        <span class="hljs-string">'(\\?[;&amp;a-z\\d%_.~+=-]*)?'</span>+ <span class="hljs-comment">// validate query string</span>
        <span class="hljs-string">'(\\#[-a-z\\d_]*)?$'</span>,<span class="hljs-string">'i'</span>); <span class="hljs-comment">// validate fragment locator</span>
      <span class="hljs-keyword">return</span> !!urlPattern.test(urlString);
    }
</code></pre>
<h3 id="heading-how-to-use-regex-to-validate-a-url-string">How to use regex to validate a URL string</h3>
<p>The code below demonstrates how to validate different URL strings using the above method:</p>
<pre><code class="lang-js">    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"invalidURL"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));      <span class="hljs-comment">//false</span>

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"htt//jsowl"</span>;            <span class="hljs-comment">//false</span>
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"www.jsowl.com"</span>;         <span class="hljs-comment">//true</span>
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com"</span>; <span class="hljs-comment">//true</span>
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));      <span class="hljs-comment">//true</span>
</code></pre>
<h2 id="heading-how-to-check-if-a-string-is-a-valid-url-using-url-constructor">How to Check if a String is a Valid URL using URL Constructor</h2>
<p>You can use the URLConstructor to check if a string is a valid URL.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL">URLConstructor</a> (<code>new URL(url)</code>) returns a newly created URL object defined by the URL parameters.</p>
<p>A JavaScript <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError"><code>TypeError</code></a> exception is thrown if the given URL is not valid.</p>
<p><strong>Note:</strong> It is appropriate to use this method when you want to construct a URL object in your program for further uses.</p>
<h3 id="heading-url-constructor-syntax">URL Constructor Syntax</h3>
<p>The following syntax explains how to create a URL Object with a JavaScript String.</p>
<pre><code><span class="hljs-keyword">new</span> URL(url);
<span class="hljs-keyword">new</span> URL(url, base);
</code></pre><p>Where,</p>
<ul>
<li><code>url</code> is a string or any object with a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Stringifier">stringifier</a> that represents an absolute or relative URL. If <strong>URL</strong> is an absolute URL, <strong>base</strong> shall be ignored. If <strong>URL</strong> is a relative URL, <strong>base</strong> is required.</li>
<li><code>base</code> (optional) is a string representing the base URL. It must be passed when the URL is relative. Defaults to <em>undefined</em> when ignored.</li>
</ul>
<h3 id="heading-example-of-url-constructor-method">Example of URL Constructor method</h3>
<p>To demonstrate how the URL constructor method works, let's create a lambda function in JavaScript to construct a new URL with the passed string.</p>
<ul>
<li>If the string is a valid URL, a URL object is created, and <code>true</code> is returned</li>
<li>If the String is not a valid URL, a <code>Tyeperror</code> exception is thrown, and <code>false</code> is returned</li>
</ul>
<pre><code><span class="hljs-keyword">const</span> isValidUrl = <span class="hljs-function"><span class="hljs-params">urlString</span>=&gt;</span> {
      <span class="hljs-keyword">try</span> { 
          <span class="hljs-keyword">return</span> <span class="hljs-built_in">Boolean</span>(<span class="hljs-keyword">new</span> URL(urlString)); 
      }
      <span class="hljs-keyword">catch</span>(e){ 
          <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; 
      }
  }
</code></pre><h3 id="heading-how-to-use-the-isvalidurl-method">How to use the <code>isValidURL()</code> method</h3>
<p>Let's invoke the <code>isValidURL()</code> method for different string types and see the results.</p>
<pre><code>  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"invalidURL"</span>;
  <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//false</span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"htt//jsowl"</span>;
  <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//false</span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"www.jsowl.com"</span>;
  <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//false</span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"tcp://www.jsowl.com"</span>;
  <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//true</span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/"</span>;
  <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//true</span>
</code></pre><p>In the first three cases, you can see that <em>an invalid URL string</em> is passed. As a result, URL object creation fails with a <code>TypeError</code> and <code>false</code> is returned.</p>
<p>In the last two cases, <em>valid URL string</em> is passed. So a <code>URL</code> object is created successfully, and <code>True</code> is returned, confirming the proper URL.</p>
<p>Let's see one more example to validate a specific URL part.</p>
<p>In this example, you are validating a specific protocol in the URL. The URL must contain the <code>http</code> or <code>https</code> protocol.</p>
<pre><code>    <span class="hljs-keyword">const</span> isValidUrl = <span class="hljs-function"><span class="hljs-params">urlString</span>=&gt;</span> {
        <span class="hljs-keyword">let</span> url;
        <span class="hljs-keyword">try</span> { 
              url =<span class="hljs-keyword">new</span> URL(urlString); 
        }
        <span class="hljs-keyword">catch</span>(e){ 
          <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; 
        }
        <span class="hljs-keyword">return</span> url.protocol === <span class="hljs-string">"http:"</span> || url.protocol === <span class="hljs-string">"https:"</span>;
    }
</code></pre><h3 id="heading-example-of-how-to-validate-part-of-a-url">Example of how to validate part of a URL</h3>
<p>Let's invoke the <code>isValidURL()</code> method for different string types and protocols and see the results.</p>
<pre><code><span class="hljs-keyword">var</span> url = <span class="hljs-string">"tcp://www.jsowl.com"</span>;
<span class="hljs-built_in">console</span>.log(isValidUrl(url));      <span class="hljs-comment">//false</span>

<span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com"</span>;
<span class="hljs-built_in">console</span>.log(isValidUrl(url));      <span class="hljs-comment">//true</span>
</code></pre><p>In the first case, the URL string <em>(tcp://www.jsowl.com)</em> is valid, but it doesn't contain a specific protocol (<code>HTTP</code>/<code>HTTPS</code>). So it returns <em>false</em>.</p>
<p>In the second case, the URL string <em><a target="_blank" href="https://www.jsowl.com">https://www.jsowl.com</a></em> is <em>valid</em> and contains the specific protocol. So it returns <em>true</em>.</p>
<h2 id="heading-how-to-check-if-a-string-is-a-valid-url-using-an-input-element">How to Check if a String is a Valid URL Using an Input Element</h2>
<p>HTML supports an input element with type <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url"><code>url</code></a>,  specifically for representing URL values.</p>
<p>The <code>&lt;input&gt;</code> element's <code>value</code> attribute containing the string is automatically validated by matching the URL syntax (<em>either has an empty or properly formed URL</em>) before the form can be submitted.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity"><code>HTMLInputElement.checkValidity()</code></a> method is used to check if a string in  <code>&lt;input&gt;</code> element’s value attribute is <code>URL</code>. The <code>checkvalidity()</code> method returns <code>true</code> if the value is a proper URL and <code>false</code> if the input is not a proper URL.</p>
<p>Let's create a method which creates an input element type <code>URL</code> and validates the input using the <code>checkValidity()</code> method.</p>
<pre><code>    <span class="hljs-keyword">const</span> isValidUrl = <span class="hljs-function"><span class="hljs-params">urlString</span> =&gt;</span>{
      <span class="hljs-keyword">var</span> inputElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'input'</span>);
      inputElement.type = <span class="hljs-string">'url'</span>;
      inputElement.value = urlString;

      <span class="hljs-keyword">if</span> (!inputElement.checkValidity()) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
      }
    }
</code></pre><p>Now let's use this method and validate different strings to see if they are valid URLs.</p>
<pre><code>    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"invalidURL"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//false</span>

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"htt//jsowl"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//false</span>

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"www.jsowl.com"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//false</span>

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//true</span>

    <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/"</span>;
    <span class="hljs-built_in">console</span>.log(isValidUrl(url));     <span class="hljs-comment">//true</span>
</code></pre><p>This is how you can use the input type method to check if a string is a valid URL.</p>
<h2 id="heading-how-to-check-if-a-string-is-a-valid-url-using-the-anchor-tag-method">How to Check if a String is a Valid URL Using the Anchor Tag Method</h2>
<p>This section teaches you how to use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement">HTMLAnchorElement</a> to check whether a JavaScript string is a URL.</p>
<p><strong>Note:</strong> It is appropriate to use this method when you want to assign a URL to the <code>anchor</code> tag of your webpage and ensure that the URL string is valid and gets assigned to the <code>anchor</code> tag properly.</p>
<p>The <code>HTMLAnchorElement</code> interface represents hyperlink elements. It provides special properties and methods for manipulating the layout and presentation of such elements. It is also called an anchor tag.</p>
<p>You can assign a URL to an anchor tag using the <code>href</code> attribute. While assigning,</p>
<ul>
<li>If a valid URL string is passed, it is assigned to the anchor tag</li>
<li>If an invalid URL is passed, the <a target="_blank" href="https://www.jsowl.com/how-to-get-the-current-url-in-jquery/">current browser location</a> is assigned to the anchor tag</li>
<li>By default, the anchor tag will have an empty URL (“”)</li>
</ul>
<p>Once the URL is assigned, you can extract a specific part of the URL using the attributes explained below.</p>
<table>
<thead>
<tr>
<th>HTMLAnchorElement atribute</th>
<th>usage</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>host</code></td>
<td>a string representing hostname and port</td>
</tr>
<tr>
<td><code>hostname</code></td>
<td>a string representing hostname</td>
</tr>
<tr>
<td><code>href</code></td>
<td>a string containing a valid URL</td>
</tr>
<tr>
<td><code>origin</code></td>
<td>returns a string containing the origin, its schema, domain name and port</td>
</tr>
<tr>
<td><code>port</code></td>
<td>a string representing the port if specified</td>
</tr>
<tr>
<td><code>protocol</code></td>
<td>a string representing the protocol including the trailing('<code>:</code>')</td>
</tr>
<tr>
<td><code>pathname</code></td>
<td>a string containing the path URL from initial (/) and not including the query string</td>
</tr>
</tbody>
</table>

<p>Now, let's see how to check if the assigned string was a proper URL.</p>
<p>If it was a proper URL, it would be assigned to the anchor tag. Else, the current browser location will be assigned to the anchor tag.</p>
<p>So to check if it was a proper URL, you can check if the anchor tag’s <code>host</code> is NOT equal to the current location using the statement <code>a.host != window.location.host</code>.</p>
<p>Let's look at the code.</p>
<p>We create a lambda function and assign it to the constant <code>isValidUrl</code> in the code below.</p>
<p>The function creates an anchor tag element and assigns the URL string to the anchor tag. After that, it checks if the <code>host</code> attribute of the element is <code>null</code> or not defined.</p>
<p>If it is not null, it checks whether the <code>host</code> attribute is NOT equal to the current browser URL and returns <code>True</code> when it is not equal. </p>
<p>This is because if the passed URL was valid, then the anchor tag will have the URL value. But if the passed URL was invalid, the anchor tag will have the current browser location. In this case, the lambda function returns <code>False</code>.</p>
<pre><code><span class="hljs-keyword">const</span> isValidUrl = <span class="hljs-function"><span class="hljs-params">urlString</span> =&gt;</span>{    
      <span class="hljs-keyword">var</span> a  = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'a'</span>);
       a.href = urlString;
       <span class="hljs-keyword">return</span> (a.host &amp;&amp; a.host != <span class="hljs-built_in">window</span>.location.host);
  }
</code></pre><p>The below code snippets invoke the lambda function <code>isValidUrl()</code> with different inputs and print the output accordingly in the console.</p>
<pre><code class="lang-js">  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"invalidURL"</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1.AnchorTag:  "</span> +isValidUrl(url));    <span class="hljs-comment">//false</span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"htt//jsowl"</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"22.AnchorTag:  "</span>+isValidUrl(url));    <span class="hljs-comment">//false</span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"www.jsowl.com"</span>;  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"3.AnchorTag:  "</span> +isValidUrl(url));    <span class="hljs-comment">//false  </span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com"</span>;  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"4.AnchorTag:  "</span> +isValidUrl(url));    <span class="hljs-comment">//true </span>

  <span class="hljs-keyword">var</span> url = <span class="hljs-string">"https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/"</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"5.AnchorTag:  "</span> +isValidUrl(url));    <span class="hljs-comment">//true</span>
</code></pre>
<p>This tutorial is available in <a target="_blank" href="https://jsfiddle.net/jsowl/mvzqh4of/266/">this</a> JSFiddle.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you've learned how to check if a JavaScript string is a <code>URL</code> using different methods and when it is appropriate to use each method.</p>
<p>If you liked this article, feel free to share it.</p>
<p>You can <a target="_blank" href="https://www.jsowl.com/">check out my other tutorials on my blog, JS Owl</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Data Analytics with Pandas – How to Drop a List of Rows from a Pandas Dataframe ]]>
                </title>
                <description>
                    <![CDATA[ A Pandas dataframe is a two dimensional data structure which allows you to store data in rows and columns. It's very useful when you're analyzing data. When you have a list of data records in a dataframe, you may need to drop a specific list of rows ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/drop-list-of-rows-from-pandas-dataframe/</link>
                <guid isPermaLink="false">66bb8ac1c332a9c775d15b63</guid>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data analytics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dataframe ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pandas ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 01 Jun 2021 20:47:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/cut_lemons--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A Pandas dataframe is a two dimensional data structure which allows you to store data in rows and columns. It's very useful when you're analyzing data.</p>
<p>When you have a list of data records in a dataframe, you may need to drop a specific list of rows depending on the needs of your model and your goals when studying your analytics. </p>
<p>In this tutorial, you'll learn how to drop a list of rows from a Pandas dataframe. </p>
<p>To learn how to drop columns, you can read here about <a target="_blank" href="https://www.stackvidhya.com/drop-column-in-pandas/">How to Drop Columns in Pandas</a>. </p>
<h2 id="heading-how-to-drop-a-row-or-column-in-a-pandas-dataframe">How to Drop a Row or Column in a Pandas Dataframe</h2>
<p>To drop a row or column in a dataframe, you need to use the <code>drop()</code> method available in the dataframe. You can read more about the <code>drop()</code> method in the docs <a target="_blank" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html">here</a>. </p>
<p><strong>Dataframe Axis</strong></p>
<ul>
<li>Rows are denoted using <code>axis=0</code></li>
<li>Columns are denoted using <code>axis=1</code></li>
</ul>
<p><strong>Dataframe Labels</strong></p>
<ul>
<li>Rows are labelled using the index number starting with 0, by default.</li>
<li>Columns are labelled using names. </li>
</ul>
<p><strong>Drop() Method Parameters</strong></p>
<ul>
<li><code>index</code> - the list of rows to be deleted</li>
<li><code>axis=0</code> - Marks the rows in the dataframe to be deleted</li>
<li><code>inplace=True</code> - Performs the drop operation in the same dataframe, rather than creating a new dataframe object during the delete operation. </li>
</ul>
<h3 id="heading-sample-pandas-dataframe">Sample Pandas DataFrame</h3>
<p>Our sample dataframe contains the columns <em>product_name</em>, <em>Unit_Price</em>, <em>No_Of_Units</em>, <em>Available_Quantity</em>, and <em>Available_Since_Date</em> columns. It also has rows with NaN values which are used to denote missing values. </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {<span class="hljs-string">"product_name"</span>:[<span class="hljs-string">"Keyboard"</span>,<span class="hljs-string">"Mouse"</span>, <span class="hljs-string">"Monitor"</span>, <span class="hljs-string">"CPU"</span>,<span class="hljs-string">"CPU"</span>, <span class="hljs-string">"Speakers"</span>,pd.NaT],
        <span class="hljs-string">"Unit_Price"</span>:[<span class="hljs-number">500</span>,<span class="hljs-number">200</span>, <span class="hljs-number">5000.235</span>, <span class="hljs-number">10000.550</span>, <span class="hljs-number">10000.550</span>, <span class="hljs-number">250.50</span>,<span class="hljs-literal">None</span>],
        <span class="hljs-string">"No_Of_Units"</span>:[<span class="hljs-number">5</span>,<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">20</span>, <span class="hljs-number">8</span>,pd.NaT],
        <span class="hljs-string">"Available_Quantity"</span>:[<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">10</span>,<span class="hljs-string">"Not Available"</span>,<span class="hljs-string">"Not Available"</span>, pd.NaT,pd.NaT],
        <span class="hljs-string">"Available_Since_Date"</span>:[<span class="hljs-string">'11/5/2021'</span>, <span class="hljs-string">'4/23/2021'</span>, <span class="hljs-string">'08/21/2021'</span>,<span class="hljs-string">'09/18/2021'</span>,<span class="hljs-string">'09/18/2021'</span>,<span class="hljs-string">'01/05/2021'</span>,pd.NaT]
       }

df = pd.DataFrame(data)

df
</code></pre>
<p>The dataframe will look like this:</p>
<div>

<table>
  <thead>
    <tr>
      <th></th>
      <th>product_name</th>
      <th>Unit_Price</th>
      <th>No_Of_Units</th>
      <th>Available_Quantity</th>
      <th>Available_Since_Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Keyboard</td>
      <td>500.000</td>
      <td>5</td>
      <td>5</td>
      <td>11/5/2021</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Mouse</td>
      <td>200.000</td>
      <td>5</td>
      <td>6</td>
      <td>4/23/2021</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Monitor</td>
      <td>5000.235</td>
      <td>10</td>
      <td>10</td>
      <td>08/21/2021</td>
    </tr>
    <tr>
      <th>3</th>
      <td>CPU</td>
      <td>10000.550</td>
      <td>20</td>
      <td>Not Available</td>
      <td>09/18/2021</td>
    </tr>
    <tr>
      <th>4</th>
      <td>CPU</td>
      <td>10000.550</td>
      <td>20</td>
      <td>Not Available</td>
      <td>09/18/2021</td>
    </tr>
    <tr>
      <th>5</th>
      <td>Speakers</td>
      <td>250.500</td>
      <td>8</td>
      <td>NaT</td>
      <td>01/05/2021</td>
    </tr>
    <tr>
      <th>6</th>
      <td>NaT</td>
      <td>NaN</td>
      <td>NaT</td>
      <td>NaT</td>
      <td>NaT</td>
    </tr>
  </tbody>
</table>
</div>

<p>And just like that we've created our sample dataframe. </p>
<p>After each drop operation, you'll print the dataframe by using <code>df</code> which will print the dataframe in a regular <code>HTML</code> table format. </p>
<p>You can read here about how to <a target="_blank" href="https://www.stackvidhya.com/pretty-print-dataframe/">Pretty Print a Dataframe</a> to print the dataframe in different visual formats. </p>
<p>Next, you'll learn how to drop a list of rows in different use cases. </p>
<h2 id="heading-how-to-drop-a-list-of-rows-by-index-in-pandas">How to Drop a List of Rows by Index in Pandas</h2>
<p>You can delete a list of rows from Pandas by passing the list of indices to the <code>drop()</code> method. </p>
<pre><code class="lang-python">df.drop([<span class="hljs-number">5</span>,<span class="hljs-number">6</span>], axis=<span class="hljs-number">0</span>, inplace=<span class="hljs-literal">True</span>)

df
</code></pre>
<p>In this code,</p>
<ul>
<li><code>[5,6]</code> is the index of the rows you want to delete</li>
<li><code>axis=0</code> denotes that rows should be deleted from the dataframe</li>
<li><code>inplace=True</code> performs the drop operation in the same dataframe</li>
</ul>
<p>After dropping rows with the index 5 and 6, you'll have the below data in the dataframe:</p>
<div>

<table>
  <thead>
    <tr>
      <th></th>
      <th>product_name</th>
      <th>Unit_Price</th>
      <th>No_Of_Units</th>
      <th>Available_Quantity</th>
      <th>Available_Since_Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Keyboard</td>
      <td>500.000</td>
      <td>5</td>
      <td>5</td>
      <td>11/5/2021</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Mouse</td>
      <td>200.000</td>
      <td>5</td>
      <td>6</td>
      <td>4/23/2021</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Monitor</td>
      <td>5000.235</td>
      <td>10</td>
      <td>10</td>
      <td>08/21/2021</td>
    </tr>
    <tr>
      <th>3</th>
      <td>CPU</td>
      <td>10000.550</td>
      <td>20</td>
      <td>Not Available</td>
      <td>09/18/2021</td>
    </tr>
    <tr>
      <th>4</th>
      <td>CPU</td>
      <td>10000.550</td>
      <td>20</td>
      <td>Not Available</td>
      <td>09/18/2021</td>
    </tr>
  </tbody>
</table>
</div>

<p>This is how you can delete rows with a specific index. </p>
<p>Next, you'll learn about dropping a range of indices. </p>
<h2 id="heading-how-to-drop-rows-by-index-range-in-pandas">How to Drop Rows by Index Range in Pandas</h2>
<p>You can also drop a list of rows within a specific range. </p>
<p>A range is a set of values with a lower limit and an upper limit. </p>
<p>This may be useful in cases where you want to create a sample dataset exlcuding specific ranges of data. </p>
<p>You can create a range of rows in a dataframe by using the <code>df.index()</code> method. Then you can pass this range to the <code>drop()</code> method to drop the rows as shown below. </p>
<pre><code class="lang-python">df.drop(df.index[<span class="hljs-number">2</span>:<span class="hljs-number">4</span>], inplace=<span class="hljs-literal">True</span>)

df
</code></pre>
<p>Here's what this code is doing:</p>
<ul>
<li><code>df.index[2:4]</code> generates a range of rows from 2 to 4. The lower limit of the range is inclusive and the upper limit of the range is exclusive. This means that rows 2 and 3 will be deleted and row 4 will <em>not</em> be deleted. </li>
<li><code>inplace=True</code> performs the drop operation in the same dataframe</li>
</ul>
<p>After dropping rows within the range 2-4, you'll have the below data in the dataframe:</p>
<div>

<table>
  <thead>
    <tr>
      <th></th>
      <th>product_name</th>
      <th>Unit_Price</th>
      <th>No_Of_Units</th>
      <th>Available_Quantity</th>
      <th>Available_Since_Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Keyboard</td>
      <td>500.00</td>
      <td>5</td>
      <td>5</td>
      <td>11/5/2021</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Mouse</td>
      <td>200.00</td>
      <td>5</td>
      <td>6</td>
      <td>4/23/2021</td>
    </tr>
    <tr>
      <th>4</th>
      <td>CPU</td>
      <td>10000.55</td>
      <td>20</td>
      <td>Not Available</td>
      <td>09/18/2021</td>
    </tr>
  </tbody>
</table>
</div>

<p>This is how you can drop the list of rows in the dataframe using its range. </p>
<h2 id="heading-how-to-drop-all-rows-after-an-index-in-pandas">How to Drop All Rows after an Index in Pandas</h2>
<p>You can drop all rows after a specific index by using <code>iloc[]</code>. </p>
<p>You can use <code>iloc[]</code> to select rows by using its position index. You can specify the start and end position separated by a <code>:</code>. For example, you'd use <code>2:3</code> to select rows from 2 to 3. If you want to select all the rows, you can just use <code>:</code> in <code>iloc[]</code>. </p>
<p>This may be useful in cases where you want to split the dataset for training and testing purposes. </p>
<p>Use the below snippet to select rows from 0 to the index 2. This results in dropping the rows after the index 2. </p>
<pre><code class="lang-python">df = df.iloc[:<span class="hljs-number">2</span>]

df
</code></pre>
<p>In this code, <code>:2</code> selects the rows until the index 2. </p>
<p>This is how you can drop all rows after a specific index. </p>
<p>After dropping rows after the index 2, you'll have the below data in the dataframe:</p>
<div>

<table>
  <thead>
    <tr>
      <th></th>
      <th>product_name</th>
      <th>Unit_Price</th>
      <th>No_Of_Units</th>
      <th>Available_Quantity</th>
      <th>Available_Since_Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Keyboard</td>
      <td>500.0</td>
      <td>5</td>
      <td>5</td>
      <td>11/5/2021</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Mouse</td>
      <td>200.0</td>
      <td>5</td>
      <td>6</td>
      <td>4/23/2021</td>
    </tr>
  </tbody>
</table>
</div>

<p>This is how you can drop rows after a specific index. </p>
<p>Next, you'll learn how to drop rows with conditions. </p>
<h2 id="heading-how-to-drop-rows-with-multiple-conditions-in-pandas">How to Drop Rows with Multiple Conditions in Pandas</h2>
<p>You can drop rows in the dataframe based on specific conditions. </p>
<p>For example, you can drop rows where the column value is greater than <em>X</em> and less than <em>Y</em>. </p>
<p>This may be useful in cases where you want to create a dataset that ignores columns with specific values. </p>
<p>To drop rows based on certain conditions, select the index of the rows which pass the specific condition and pass that index to the <code>drop()</code> method.  </p>
<pre><code class="lang-python">df.drop(df[(df[<span class="hljs-string">'Unit_Price'</span>] &gt;<span class="hljs-number">400</span>) &amp; (df[<span class="hljs-string">'Unit_Price'</span>] &lt; <span class="hljs-number">600</span>)].index, inplace=<span class="hljs-literal">True</span>)

df
</code></pre>
<p>In this code, </p>
<ul>
<li><code>(df['Unit_Price'] &gt;400) &amp; (df['Unit_Price'] &lt; 600)</code> is the condition to drop the rows. </li>
<li><code>df[].index</code> selects the index of rows which passes the condition. </li>
<li><code>inplace=True</code> performs the drop operation in the same dataframe rather than creating a new one.</li>
</ul>
<p>After dropping the rows with the condition which has the <code>unit_price</code> greater than 400 and less than 600, you'll have the below data in the dataframe:</p>
<div>

<table>
  <thead>
    <tr>
      <th></th>
      <th>product_name</th>
      <th>Unit_Price</th>
      <th>No_Of_Units</th>
      <th>Available_Quantity</th>
      <th>Available_Since_Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>Mouse</td>
      <td>200.0</td>
      <td>5</td>
      <td>6</td>
      <td>4/23/2021</td>
    </tr>
  </tbody>
</table>
</div>

<p>This is how you can drop rows in the dataframe using certain conditions. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>To summarize, in this article you've learnt what the <code>drop()</code> method is in a Pandas dataframe. You've also seen how dataframe rows and columns are labelled. And finally you've learnt how to drop rows using indices, a range of indices, and based on conditions. </p>
<p>If you liked this article, feel free to share it. </p>
<h3 id="heading-you-may-also-like">You May Also Like</h3>
<ul>
<li><a target="_blank" href="https://www.stackvidhya.com/add-column-to-dataframe/">How to Add a Column to a Dataframe in Pandas</a><ul>
<li><a target="_blank" href="https://www.stackvidhya.com/rename-column-in-pandas/">How to Rename a Column in Pandas</a></li>
</ul>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
