Last modified: Jan 10, 2023 By Alexander Williams
Python: Check if String is URL
In this article, we will discover two methods to check if a string is a URL.
Checking if a string is a URL using the validators library
First, we need to install validators using pip.
pip install validators
How to use it:
validators.url(string)
The validators.url method returns True if a string is a URL, else returns False.
Example of checking a string:
import validators
string = "https://pytutorial.com"
print(validators.url(string))
Output:
True
Example #2
import validators
string = "https://pytutorial.com"
if validators.url(string) is True:
print("it's URL")
Output:
it's URL
Checking if a string is a URL using Regular Expression (Regex)
import re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
string = "https://pytutorial.com"
print(re.match(regex, string) is not None )
Output
True