Skip to content

Effortlessly Replace Space with Underscore in Python

[

In this Python tutorial, we will learn how to replace spaces with underscores in all H2 and H3 headings. This step-by-step guide will provide you with executable sample codes and explanations to help you understand the process.

  • Step 1: Import the required libraries.
import re
from bs4 import BeautifulSoup
  • Step 2: Define a function to replace spaces with underscores.
def replace_spaces_with_underscore(text):
return text.replace(" ", "_")
  • Step 3: Load the HTML file containing the headings.
with open("index.html") as file:
html_data = file.read()
  • Step 4: Parse the HTML file using BeautifulSoup.
soup = BeautifulSoup(html_data, "html.parser")
  • Step 5: Find all the H2 and H3 headings using BeautifulSoup’s find_all method.
headings = soup.find_all(["h2", "h3"])
  • Step 6: Iterate over the headings and replace spaces with underscores using the previously defined function.
for heading in headings:
heading.string = replace_spaces_with_underscore(heading.string)
  • Step 7: Save the modified HTML file.
with open("modified.html", "w") as file:
file.write(str(soup))

Congratulations! You have successfully replaced spaces with underscores in all H2 and H3 headings. The modified HTML file can be found as “modified.html”.

This tutorial provided you with detailed, executable sample codes to achieve the desired task. By following the step-by-step instructions, you were able to replace spaces with underscores in all H2 and H3 headings using Python.