Home > Software design >  Check if a list contains the string input by the user
Check if a list contains the string input by the user

Time:10-19

Firstly, I've checked several possible solutions but they don't have the solution to my problem.

Given below is my code:

import webbrowser

webstr = ['https://','http://','www.','.com','.co.','.org','.net','.org','.gov','.edu','.nic']
search_string = input("Search Google or Type a URL: ")

if len(search_string)<1:
     webbrowser.open_new_tab("https://www.google.com")
     print("Opening Google.")

elif webstr in search_string:
     webbrowser.open_new_tab(search_string)
     print("Opening",search_string)

elif webstr not in search_string:
     webbrowser.open_new_tab("https://www.google.com/search?q="   search_string)
     print("Searching Google for", search_string)

What I want is an easy way to check the input string for phrases provided in the webstr list and if any phrase match, accordingly open the url in the browser. If the phrases are not in the list, it should search the browser for the given string or if search string is too short, then it should return to the website so said.

P.S. It is my 1st time asking a question and I am new to Python.

CodePudding user response:

You want to see if any of the fields present in webstr list is a substring of the input. You can do it as below:

if any(x in search_string for x in webstr)

The below code should work for your use case

import webbrowser

webstr = ['https://','http://','www.','.com','.co.','.org','.net','.org','.gov','.edu','.nic']
search_string = input("Search Google or Type a URL: ")

if len(search_string)<1:
     webbrowser.open_new_tab("https://www.google.com")
     print("Opening Google.")

elif any(x in search_string for x in webstr):
     webbrowser.open_new_tab(search_string)
     print("Opening",search_string)

else:
     webbrowser.open_new_tab("https://www.google.com/search?q="   search_string)
     print("Searching Google for", search_string)
  • Related