36

Suppose I have the following string:

"http://earth.google.com/gallery/kmz/women_for_women.kmz?a=large"

Is there some function or module to be able to convert a string like the above to a string below where all the characters are changed to be compliant with a url:

"http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge"

What is the best way to do this in python?

3 Answers 3

45

Python 2's urllib.quote_plus, and Python 3's urllib.parse.quote_plus

url = "http://earth.google.com/gallery/kmz/women_for_women.kmz?a=large"
# Python 2
urllib.quote_plus(url)
# Python 3
urllib.parse.quote_plus(url)

outputs:

'http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge'
Sign up to request clarification or add additional context in comments.

3 Comments

I think there's an issue when you want to have a space become %2C and it gets converted to a + instead.
Also, as an update, you need to use urllib.parse.quote_plus in Python 3
@MaxCandocia Yes, that's the job of quote_plus, it converts spaces to +, hence the name. The docs talk about the difference... quote is for URL path components, and quote_plus is for query string parameter names and values.
11

Available in the Windows platform

#! python3.6
from urllib.parse import quote


# result: http://www.oschina.net/search?scope=bbs&q=C%E8%AF%AD%E8%A8%80
quote('http://www.oschina.net/search?scope=bbs&q=C语言',safe='/:?=&')

2 Comments

The user asked for all special characters to be converted
@DeadSec this question is over three years old at this point, but just because the OP didn't understand the code doesn't mean they shouldn't be coding. Everyone takes time to learn and you cant expect them to understand everything immediately. Have a little patience. Peace.
2

Are you looking for urllib.quote or urllib.quote_plus? Note that you do not quote the entire url string as you mentioned in the question. You normally quote the part in the path or after the query string. Whichever you are going to use in the application.

2 Comments

you'd quote the entire url if it were just a string that is part of a GET request. e.g. http://example.com/show-url-info?url=http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge
In this, the full query is part of the query.

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.