how to convert a string into url in python

Viewed 1160

I have a string with the following format: foo://bar_baz.
I need to encode the entire string to be URL friendly. Right now I am doing it like so (as most answers seem to point):

from urllib.parse import urlencode
mydict = {'q': 'foo://bar_baz'}
urlencode(mydic)

which returns:

'q=foo%3A%2F%2Fbar_baz'

I can use this without problem, but it seems counterintuitive / extra steps to have to define a dictionary, and assign a key (in this case q) that I will not be using. Moreover, I need to go through the step of properly parsing the output to remove the q= as I only need to encode the value for the key q. Spliting by q= could do it, but what if foo/bar/baz are actualy fooq= ? it might break stuff.

I was hoping to do something like:

# pass a string instead of a dict
encoded_string = urlencode("foo://bar_baz")

but that of course raises error.

1 Answers

ok I just needed to google a bit more.

urllib.parse.quote_plus("foo://bar_baz")

did the trick.

Related