David542
David542

Reputation: 110382

URLEncoding from a string

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 = ?

Upvotes: 0

Views: 62

Answers (2)

Wolph
Wolph

Reputation: 80061

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?

Upvotes: 1

aseeon
aseeon

Reputation: 323

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))

Upvotes: 1

Related Questions