'What is the best way to make sure a string doesn't contain a link

What's the best and clean way to make sure a string doesn't contain a link https:// or http:// or even only the address (www.google.com) without http(s) with the built-in libraries



Solution 1:[1]

Its enough to write an if statement:

str1="https://www.google.com"
keyword="https://"
if keyword in str1:
    print("The chosen string contains a website link")

Solution 2:[2]

This might be sufficient for quite many examples:

str1="https://www.google.com"
str2="http://www.google.com"
str3="www.google.com"
str4="www.google"
str5="http://google"

def check_if_url(inp):
    is_url=False
    if inp.count(".")>=2:
        is_url=True
    return(is_url)

check_if_url(str1)
check_if_url(str2)
check_if_url(str3)
check_if_url(str4)
check_if_url(str5)

>>> True
>>> True
>>> True
>>> False
>>> False

Solution 3:[3]

You can use the validators library.

>>> import validators
ValidationFailure(func=url, args={'value': '1213', 'public': False})
>>> validators.url("https://stackoverflow.com/questions/56086236/what-is-the-best-way-to-make-sure-a-string-doesnt-contain-a-link")
True
>>> validators.url("htt\ps://stackoverflow.com/questions/56086236/what-is-the-best-way-to-make-sure-a-string-doesnt-contain-a-link")
ValidationFailure(func=url, args={'value': 'htt\\ps://stackoverflow.com/questions/56086236/what-is-the-best-way-to-make-sure-a-string-doesnt-contain-a-link', 'public': False})
>>> validators.url("https://stackoverflow/questions/56086236/what-is-the-best-way-to-make-sure-a-string-doesnt-contain-a-link")
ValidationFailure(func=url, args={'value': 'https://stackoverflow/questions/56086236/what-is-the-best-way-to-make-sure-a-string-doesnt-contain-a-link', 'public': False})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DovaX
Solution 2 DovaX
Solution 3 Rinkesh P