Home > database >  trying to separate the string and insert it in a different position
trying to separate the string and insert it in a different position

Time:09-05

does anyone know how to separate this string and put it in base_url in a different position like this:

movie = ("Burning 2018")
base_url = ("http://www.omdbapi.com/?t=" (Burning) "&y=" (2018) "&apikey=")

This is my code:

movie = ("Burning 2018")
base_url = ("http://www.omdbapi.com/?t=" Burning "&y=" 2018 "&apikey=")
r = (requests.get(base_url))
b = r.json()
print(b)

CodePudding user response:

You can reverse split your movie variable on space, with a maximum of 1 split, to generate the title and year. Then use an f-string to generate the base_url:

movie = 'Burning 2018'
title, year = movie.rsplit(' ', 1)
base_url = f"http://www.omdbapi.com/?t={title}&y={year}&apikey="
print(base_url)

Output:

http://www.omdbapi.com/?t=Burning&y=2018&apikey=

By using reverse split, the code will still work when a movie has more than one word in the title e.g.

movie = 'Lord of the Rings 2004'
title, year = movie.rsplit(' ', 1)
base_url = f"http://www.omdbapi.com/?t={title}&y={year}&apikey="
print(base_url)

Output:

http://www.omdbapi.com/?t=Lord of the Rings&y=2004&apikey=

CodePudding user response:

import urllib.parse

title, year = movie.rsplit(maxsplit=1)
query_string = urllib.parse.urlencode({
    "t": title,
    "y": year,
    "apikey": ""
})
base_url = "http://www.omdbapi.com/?"   query_string

rsplit splits the movie starting from the right side of the string. maxsplit=1 tells it to only split once, to handle cases where the movie title contains spaces.

urlencode builds a query string using the keys and values in the provided dict. This handles cases where the movie title contains spaces, punctuation, or other special characters.

CodePudding user response:

Try this:

title = movie.split()
base_url = ("http://www.omdbapi.com/?t=" title[0] "&y=" title[1] "&apikey=")

CodePudding user response:

f-strings

question_id_no = input("What question id are you searching for?")
f"https://https://stackoverflow.com/questions/{question_id_no}"
  • Related