![]() |
A regular expression (regex) is a sequence of characters that defines a search pattern in text. To remove URLs from a string in Python, you can either use regular expressions (regex) or some external libraries like urllib.parse. The re-module in Python is used for working with regular expressions. In this article, we will see how we can remove URLs from a string in Python. Python Remove URLs from a StringBelow are the ways by which we can remove URLs from a string in Python:
Python Remove URLs from String Using re.sub() functionIn this example, the code defines a function ‘remove_urls’ to find URLs in text and replace them with a placeholder [URL REMOVED], using regular expressions for pattern matching and the re.sub() method for substitution. Python3
Output
Original Text: Visit on GeeksforGeeks Website: /archive/ Text with URLs Removed: Visit on GeeksforGeeks Website: [URL REMOVED] Remove URLs from String Using re.findall() functionIn this example, the Python code defines a function ‘remove_urls_findall’ that uses regular expressions to find all URLs using re.findall() method in a given text and replaces them with a replacement text “[URL REMOVED]”. Python3
Output: Using re.findall():
Original Text:
Check out the latest Python tutorials on GeeksforGeeks: /archive/category/python/
Text with URLs Removed:
Check out the latest Python tutorials on GeeksforGeeks: [URL REMOVED]
Remove URLs from String in Python Using re.search() functionIn this example, the Python code defines a function ‘remove_urls_search’ using regular expressions and re.search() to find and replace URLs in a given text with a replacement text “[URL REMOVED]”. Python3
Output: Using re.search():
Original Text:
Visit our website at https://horje.org/ for more information. Follow us on Twitter: @horje
Text with URLs Removed:
Visit our website at [URL REMOVED] for more information. Follow us on Twitter: @horje
Remove URLs from String Using urllib.parseIn this example, the Python code defines a function ‘remove_urls_urllib’ that uses urllib.parse to check and replace URLs in a given text with a replacement text “[URL REMOVED]”. Python3
Output
Using urllib.parse: Text with URLs Removed: Check out the GeeksforGeeks website at [URL REMOVED] for programming tutorials. |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |