Last modified: Sep 26, 2023 By Alexander Williams

Remove Links from Text in Python (3 Methods + Examples)

Example 1: Using Regular Expressions


import re

# Text with links
text_with_links = "Visit our website at example.com for more information."

# Remove links using regular expressions
pattern = r']*?\s+)?href=(["\'])(.*?)\1'
text_without_links = re.sub(pattern, '', text_with_links)

print(text_without_links)

Output:


Visit our website at  for more information.
    

Example 2: Using BeautifulSoup (HTML Parser)


from bs4 import BeautifulSoup

# Text with links
text_with_links = "Visit our website at example.com for more information."

# Parse HTML using BeautifulSoup
soup = BeautifulSoup(text_with_links, 'html.parser')

# Remove all anchor tags
for tag in soup.find_all('a'):
    tag.replace_with("")

# Get the text without links
text_without_links = soup.get_text()

# Output
print(text_without_links)
    

Output:


Visit our website at  for more information.
    

Example 3: Using Regular Expressions (Advanced)


import re

# Text with links
text_with_links = "Visit our website at example.com for more information."

# Remove links using regular expressions (advanced)
pattern = r']*?\s+)?href=(["\'])(.*?)\1'
text_without_links = re.sub(pattern, '', text_with_links)
text_without_links = re.sub(r'<.*?>', '', text_without_links)

# Output
print(text_without_links)
    

Output:


Visit our website at  for more information.