2

I am rendering a URL by user input. There if user enter a string with two words I want to print the word with + in between

Example

key = input("Enter the product :")

URL = "http://exmaple.com/"

print (URL)

User input: iPhone 11

For the above code, I get a URL as "http://exmaple.com/iphone 11"

But I want to print the URL as "http://exmaple.com/iphone+11"

Dusky Dood
  • 197
  • 3
  • 13
  • 1
    Does this answer your question? [How to urlencode a querystring in Python?](https://stackoverflow.com/questions/5607551/how-to-urlencode-a-querystring-in-python) – Maurice Meyer Mar 28 '20 at 14:56
  • 2
    `key = input("Enter the product :").strip().replace(' ','+')`? – Ch3steR Mar 28 '20 at 14:56

4 Answers4

2

try encoding the key:

import urllib.parse
key = input("Enter the product :")
path = urllib.parse.quote_plus(key)
URL = "http://exmaple.com/{}".format(path)
print (URL)
Alon Arad
  • 101
  • 7
0

a possible solution is this:

key = input("Enter the product :")  # product has to have exactly one space between
# otherwise you have to make additional checks
URL = "http://exmaple.com/{}".format(key.strip().replace(" ", "+"))

print(URL)
Sachihiro
  • 1,597
  • 2
  • 20
  • 46
0

You can make use urlparse like below:

from urllib.parse import urljoin, quote_plus
key = input("Enter the product :")
final_url = urljoin( "http://exmaple.com/", quote_plus(key))
print(final_url)

# 'http://exmaple.com/iPhone+11'

Refrence:

  1. urllib: https://docs.python.org/3/library/urllib.parse.html
  2. urljoin: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin
  3. quote_plus: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus
Rajan
  • 1,463
  • 12
  • 26
0
url = f"http://exmaple.com/{key.strip().replace(' ','+')}"
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • 1
    Code only answers can almost always be improved by the addition of some explanation of how and why they work? – Suraj Kumar Mar 29 '20 at 04:32