agiliq
agiliq

Reputation: 7758

How to do a string replace in a urlencoded string

I have a string like x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"

If I do x % 10 that fails as there are %20f etc which are being treated as format strings, so I have to do a string conactination. How can I use normal string replacements here.?

Upvotes: 1

Views: 375

Answers (3)

Thomas Ahle
Thomas Ahle

Reputation: 31614

Otherwise you can use the new-style output formatting (available since v 2.6), which doesn't rely on %:

x = 'http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D{0}&format=json'
x.format(10)

It also has the advance of not being typedependent.

Upvotes: 0

codeape
codeape

Reputation: 100816

In python string formatting, use %% to output a single % character (docs).

>>> "%d%%" % 50
'50%'

So you could replace all the % with %%, except where you want to substitute during formatting. But @Conrad Meyer's solution is obviously better in this case.

Upvotes: 0

Conrad Meyer
Conrad Meyer

Reputation: 2897

urldecode the string, do the formatting, and then urlencode it again:

import urllib

x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"
tmp = urllib.unquote(x)
tmp2 = tmp % (foo, bar)
x = urllib.quote(tmp2)

As one commenter noted, doing formatting using arbitrary user-inputted strings as the format specification is historically dangerous, and is certainly a bad idea.

Upvotes: 5

Related Questions