5

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 Answer 1

8

ok I just needed to google a bit more.

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

did the trick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.