Taking user input to then go to a specific URL in python

Viewed 28

I am in the process of making a personal assistant in python. One of the features of the personal assistant is to use Wikipedia to find information on a topic. It can already read the first 3 sentences of a Wikipedia articl, but I also want the personal assistant to open that same page in the user's default web browser. Here is a snippet of what I have tried:

# Function that fetches data from wikipedia

        if 'wikipedia' in statement:
            speak('Searching Wikipedia...')
            statement =statement.replace("wikipedia", "")
            webbrowser.open_new_tab("https://www.wikipedia.com/wiki/{statement}")
            results = wikipedia.summary(statement, sentences=3)
            speak("According to Wikipedia")
            speak_and_print(results)

But instead, it opened wikipedia.com/wiki/{statement}, which I though it might do. How can I change the ocde so that it opens a Wikipedia page, like https://wikipedia.org/wiki/Main_Page?

2 Answers

you forgot to use f strings

        if 'wikipedia' in statement:
            speak('Searching Wikipedia...')
            statement =statement.replace("wikipedia", "")
            webbrowser.open_new_tab(f"https://www.wikipedia.com/wiki/{statement}")
            results = wikipedia.summary(statement, sentences=3)
            speak("According to Wikipedia")
            speak_and_print(results)

You need to replace the tag in the string:

If you are using a version of python3 that supports f-strings (3.6 or later, I believe), then this will work: f"https://www.wikipedia.com/wiki/{statement}"

Otherwise you can use this syntax: "https://www.wikipedia.com/wiki/{}".format(statement)

Related