-1

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

xMoses
  • 17
  • 1
  • Not sure exactly what sort of "links" you want to prevent in your string, but check out [How do you validate a URL with a regular expression in Python?](https://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python?noredirect=1&lq=1) – benvc May 11 '19 at 02:45

3 Answers3

0

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")
DovaX
  • 958
  • 11
  • 16
0

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
DovaX
  • 958
  • 11
  • 16
0

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})

Rinkesh P
  • 588
  • 4
  • 13