30

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?

Levon
  • 138,105
  • 33
  • 200
  • 191
Rolando
  • 58,640
  • 98
  • 266
  • 407

3 Answers3

38

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'
maij
  • 4,094
  • 2
  • 12
  • 28
Colin Dunklau
  • 3,001
  • 1
  • 20
  • 19
  • 1
    I think there's an issue when you want to have a space become `%2C` and it gets converted to a `+` instead. – Max Candocia Sep 19 '18 at 20:12
  • 1
    Also, as an update, you need to use `urllib.parse.quote_plus` in Python 3 – Max Candocia Sep 19 '18 at 20:12
  • 2
    @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. – Colin Dunklau Sep 20 '18 at 20:51
10

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='/:?=&')
Jason Yang
  • 101
  • 1
  • 3
  • The user asked for all special characters to be converted – dangee1705 Jan 03 '18 at 12:51
  • 1
    @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. – dangee1705 Feb 23 '21 at 12:13
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.

Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131