How to add a + sign in-between two words

Viewed 104

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"

4 Answers

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)

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)
url = f"http://exmaple.com/{key.strip().replace(' ','+')}"
Related