0

I am familiar with urlencode, which encodes a dictionary of parameters. How would I encode a string such as the following to a url-safe string?

s =     'http://google.com/search?q=' 
     +  'パイレーツ・オブ・カリビアン/呪われた海賊たち(日本語吹替版)' 
     + ' ' 
     + 'site:imdb.com/title'

urlencoded_str = ?
David542
  • 104,438
  • 178
  • 489
  • 842
  • What do you mean by url-safe string? Most browsers, i.e. non-internet explorer, support unicode in urls :) – Wolph Nov 02 '14 at 19:24
  • Well, the parentheticals and such wouldn't be interpreted correctly. – David542 Nov 02 '14 at 19:27
  • Possible duplicate of http://stackoverflow.com/questions/1695183/how-to-percent-encode-url-parameters-in-python – Kos Nov 02 '14 at 19:29

2 Answers2

1

Here's one possibility (the encoding line is to tell Python the encoding of the file):

# vim: encoding=utf-8

import urllib

base_url = 'http://google.com/search'
params = dict(
    q=('パイレーツ・オブ・カリビアン/呪われた海賊たち(日本語吹替版)'
       + ' site:imdb.com/title'))

query = urllib.urlencode(params)
print base_url + '?' + query

For better solutions look at this question: urllib.urlencode doesn't like unicode values: how about this workaround?

Community
  • 1
  • 1
Wolph
  • 78,177
  • 11
  • 137
  • 148
1

I am not 100% sure what you want to achive, but maybe something like this:

#!coding: utf-8
from urllib import quote

s = 'http://google.com/search?q={}site:wikipedia.org'

escape_me = 'パイレーツ・オブ・カリビアン/呪われた海賊たち(日本語吹替版) '

urlencoded_str = s.format(quote(escape_me))
aseeon
  • 323
  • 1
  • 6